package com.example.show_auto.ui.pages

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.ui.graphics.Brush
import androidx.compose.foundation.lazy.items
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties as WindowDialogProperties
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.*
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.TabRow
import androidx.compose.material3.Tab
import androidx.compose.runtime.*
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.material3.LocalTextStyle
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.text.input.KeyboardType
import com.example.show_auto.ui.utils.OppoCompatibilityFix
import com.example.show_auto.utils.CollectionTeamCalculator
import com.example.show_auto.utils.CollectionTeamCalculator.VegAreaItem
import com.example.show_auto.utils.CollectionTeamCalculator.JadeAreaItem
import com.example.show_auto.utils.CollectionTeamCalculator.LabItem
import com.example.show_auto.viewmodel.MainViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.collectAsState
import org.burnoutcrew.reorderable.ReorderableItem
import org.burnoutcrew.reorderable.ReorderableLazyListState
import org.burnoutcrew.reorderable.detectReorder
import org.burnoutcrew.reorderable.rememberReorderableLazyListState
import org.burnoutcrew.reorderable.reorderable
import androidx.compose.ui.draw.scale
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.runtime.LaunchedEffect
import kotlinx.coroutines.delay
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.ui.text.input.ImeAction
import com.example.show_auto.data.GameData
import com.example.show_auto.data.PersonalData
import com.example.show_auto.data.CombinationStorage
import com.example.show_auto.data.SchemeStorage
import com.example.show_auto.data.Scheme
import com.example.show_auto.data.SettingsStorage
import com.example.show_auto.data.SavedCombination
import com.example.show_auto.data.SavedChefInfo
import com.example.show_auto.data.Equip
import com.example.show_auto.data.Chef
import com.example.show_auto.data.MultiUserDataManager
import com.example.show_auto.data.PersonalDataManager
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts


// 采集结果数据结构
open class ChefResult(
    val name: String,
    val rarity: Int,
    val timeSeconds: Int,
    val owned: Boolean,
    val area: String, // 玉片区 / 菜地区 / 调料区
    val collectionDetails: String = "", // 采集点详情
    val isUltimate: Boolean = false // 是否已修炼
)

// 带技能信息的厨师结果
data class ChefResultWithSkills(
    val chefName: String,
    val chefRarity: Int,
    val chefTimeSeconds: Int,
    val chefOwned: Boolean,
    val chefArea: String,
    val chefCollectionDetails: String = "",
    val chefIsUltimate: Boolean = false,
    val critChance: Int, // 暴击率（仅技能+修炼）
    val critMaterial: Int, // 暴击素材（仅技能+修炼）
    val materialGain: Int, // 素材加成（技能+厨具）
    // 基础采集点信息
    val baseMeat: Int = 0,
    val baseFish: Int = 0,
    val baseVeg: Int = 0,
    val baseCreation: Int = 0,
    // 加成后采集点信息
    val totalMeat: Int = 0,
    val totalFish: Int = 0,
    val totalVeg: Int = 0,
    val totalCreation: Int = 0
) : ChefResult(chefName, chefRarity, chefTimeSeconds, chefOwned, chefArea, chefCollectionDetails, chefIsUltimate)

// 调料区配置数据类
data class CondItem(val name: String, val currentPeople: Int, val currentCapacity: Int)

// 小号文本输入框（文本编辑，自动保存）
@Composable
private fun SmallTextField(
    value: String,
    onValueChange: (String) -> Unit,
    onValueCommit: (String) -> Unit = {}, // 当输入完成时触发
    widthDp: Dp = 120.dp,
    modifier: Modifier = Modifier
) {
    var internalValue by remember { mutableStateOf(value) }
    var isFocused by remember { mutableStateOf(false) }
    val focusRequester = remember { FocusRequester() }
    val focusManager = LocalFocusManager.current

    LaunchedEffect(value) { internalValue = value }

    BasicTextField(
        value = internalValue,
        onValueChange = { newValue ->
            internalValue = newValue
            onValueChange(newValue)
        },
        modifier = modifier
            .width(widthDp)
            .height(24.dp)
            .background(Color.White, RoundedCornerShape(6.dp))
            .border(
                width = 1.dp, 
                color = if (isFocused) MaterialTheme.colorScheme.primary else Color(0xFF90A4AE), 
                shape = RoundedCornerShape(6.dp)
            )
            .focusRequester(focusRequester)
            .onFocusChanged { focusState ->
                val wasFocused = isFocused
                isFocused = focusState.isFocused
                // 当失去焦点时，触发保存
                if (wasFocused && !isFocused) {
                    if (internalValue.isNotBlank() && internalValue != value) {
                        onValueCommit(internalValue)
                    }
                }
            }
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            ) {
                focusRequester.requestFocus()
            }
            .pointerInput(Unit) {
                detectTapGestures(
                    onTap = { 
                        // 阻止点击事件传播到父容器
                        focusRequester.requestFocus()
                    }
                )
            },
        textStyle = TextStyle(
            color = Color.Black, 
            fontSize = 12.sp, 
            textAlign = TextAlign.Center,
            fontWeight = FontWeight.Medium
        ),
        singleLine = true,
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Text,
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = {
                if (internalValue.isNotBlank() && internalValue != value) {
                    onValueCommit(internalValue)
                }
                focusManager.clearFocus()
            }
        ),
        cursorBrush = SolidColor(Color.Black),
        decorationBox = { inner -> 
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 8.dp),
                contentAlignment = Alignment.Center
            ) { 
                inner() 
            } 
        }
    )
}

// 小号数字输入框（20dp 高度，文字居中，仅数字，带边框）
@Composable
private fun SmallNumberField(
    value: String,
    onValueChange: (String) -> Unit,
    maxValue: Int,
    fieldName: String = "",
    onValueExceed: (() -> Unit)? = null,
    onShowToast: (String) -> Unit = {},
    defaultValue: Int,
    widthDp: Dp = 40.dp,
    modifier: Modifier = Modifier
) {
    var internalValue by remember { mutableStateOf(value) }

    LaunchedEffect(value) { internalValue = value }

    BasicTextField(
        value = internalValue,
        onValueChange = { newValue ->
            val onlyDigits = newValue.isEmpty() || newValue.all { it.isDigit() }
            if (!onlyDigits) return@BasicTextField
            if (newValue.isEmpty()) {
                internalValue = newValue
                onValueChange(newValue)
                return@BasicTextField
            }
            val intVal = newValue.toIntOrNull()
            if (intVal != null) {
                if (intVal <= maxValue) {
                    internalValue = newValue
                    onValueChange(newValue)
                } else {
                    onValueExceed?.invoke()
                    internalValue = defaultValue.toString()
                    onValueChange(defaultValue.toString())
                }
            }
        },
        modifier = modifier
            .width(widthDp)
            .height(20.dp)
            .background(Color.White, RoundedCornerShape(6.dp))
            .border(1.dp, Color(0xFF90A4AE), RoundedCornerShape(6.dp)),
        textStyle = TextStyle(color = Color.Black, fontSize = 10.sp, textAlign = TextAlign.Center),
        singleLine = true,
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
        cursorBrush = SolidColor(Color.Black),
        decorationBox = { inner -> Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { inner() } }
    )
}

@Composable
private fun SmallDropdownField(
    value: Int,
    onValueChange: (Int) -> Unit,
    options: List<Int> = listOf(5, 4, 3, 2, 1),
    widthDp: Dp = 30.dp,
    modifier: Modifier = Modifier
) {
    var expanded by remember { mutableStateOf(false) }
    
    Box(modifier = modifier.width(widthDp)) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(20.dp)
                .background(Color.White, RoundedCornerShape(6.dp))
                .border(1.dp, Color(0xFF90A4AE), RoundedCornerShape(6.dp))
                .clickable { expanded = true },
            contentAlignment = Alignment.Center
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(2.dp)
            ) {
                Text(
                    text = value.toString(),
                    color = Color.Black,
                    fontSize = 10.sp,
                    textAlign = TextAlign.Center
                )
                Icon(
                    imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                    contentDescription = null,
                    tint = Color(0xFF90A4AE),
                    modifier = Modifier.size(12.dp)
                )
            }
        }
        
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier.width(widthDp)
        ) {
            options.forEach { option ->
                DropdownMenuItem(
                    text = {
                        Text(
                            text = option.toString(),
                            fontSize = 10.sp,
                            color = Color.Black,
                            textAlign = TextAlign.Center,
                            modifier = Modifier.fillMaxWidth()
                        )
                    },
                    onClick = {
                        onValueChange(option)
                        expanded = false
                    },
                    modifier = Modifier.height(24.dp)
                )
            }
        }
    }
}

@Composable
private fun CollectionDropdownField(
    value: Int,
    onValueChange: (Int) -> Unit,
    areaName: String,
    widthDp: Dp = 40.dp,
    modifier: Modifier = Modifier
) {
    // 根据地区名称获取对应的采集点选项
    val options = when (areaName) {
        "池塘" -> listOf(29, 24, 19, 14, 9, 5)
        "作坊" -> listOf(26, 21, 16, 11, 5, 1)
        "牧场" -> listOf(25, 19, 13, 6, 1)
        "鸡舍" -> listOf(24, 18, 14, 8, 4, 1)
        "猪圈" -> listOf(18, 12, 7, 5, 1)
        "菜棚" -> listOf(25, 20, 15, 8, 4, 1)
        "菜地" -> listOf(30, 22, 16, 8, 5, 1)
        "森林" -> listOf(32, 27, 17, 12, 6, 2)
        else -> listOf(value) // 如果没有匹配的地区，至少保留当前值
    }
    
    var expanded by remember { mutableStateOf(false) }
    
    Box(modifier = modifier.width(widthDp)) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(20.dp)
                .background(Color.White, RoundedCornerShape(6.dp))
                .border(1.dp, Color(0xFF90A4AE), RoundedCornerShape(6.dp))
                .clickable { expanded = true },
            contentAlignment = Alignment.Center
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(2.dp),
                modifier = Modifier.padding(horizontal = 4.dp)
            ) {
                Text(
                    text = value.toString(),
                    color = Color.Black,
                    fontSize = 10.sp,
                    textAlign = TextAlign.Center
                )
                Icon(
                    imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                    contentDescription = null,
                    tint = Color(0xFF90A4AE),
                    modifier = Modifier.size(12.dp)
                )
            }
        }
        
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier.width(widthDp)
        ) {
            options.forEach { option ->
                DropdownMenuItem(
                    text = {
                        Text(
                            text = option.toString(),
                            fontSize = 10.sp,
                            color = Color.Black,
                            textAlign = TextAlign.Center,
                            modifier = Modifier.fillMaxWidth()
                        )
                    },
                    onClick = {
                        onValueChange(option)
                        expanded = false
                    },
                    modifier = Modifier.height(24.dp)
                )
            }
        }
    }
}

/**
 * 查询采集编队页面
 * - 选择下拉框（仅"采集编队"，单选）
 * - 一键查询按钮（点击后展示真实查询结果）
 * - 结果展示样式参考"查询贵客冲突"，但将切换改为：玉片区/菜地区/调料区
 * - 实现真实的采集编队搜索逻辑
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ComprehensiveQueryPage(
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    // 获取 ViewModel 和游戏数据
    val viewModel: MainViewModel = viewModel()
    val gameData by viewModel.gameData.collectAsState()
    val personalData by viewModel.personalData.collectAsState()
    val uiState by viewModel.uiState.collectAsState()
    val context = LocalContext.current
    // 默认选择采集编队
    var selectedOption by remember { mutableStateOf<String?>("采集编队") }

    // 查询结果显示状态
    var hasQueriedResults by remember { mutableStateOf(false) }

    
    // 组合配置相关状态
    var showSavedCombinationsDialog by remember { mutableStateOf(false) }
    var showCombinationDetailsDialog by remember { mutableStateOf(false) }
    var selectedCombination by remember { mutableStateOf<SavedCombination?>(null) }
    var showSaveSuccessDialog by remember { mutableStateOf(false) }
    var combinationsRefreshTrigger by remember { mutableStateOf(0) }
    
    // 替换厨师相关状态
    var showReplaceDialog by remember { mutableStateOf(false) }
    var replaceAreaName by remember { mutableStateOf("") }
    var replaceChefName by remember { mutableStateOf("") }
    
    // 使用说明弹窗状态
    var showUsageDialog by remember { mutableStateOf(false) }
    
    // 获取组合存储实例
    val combinationStorage = remember { CombinationStorage(context) }
    
    // 查询结果状态
    var queryResults by remember { mutableStateOf<List<ChefResult>>(emptyList()) }
    // 查询计数器，用于强制刷新展开状态
    var queryCounter by remember { mutableStateOf(0) }
    
    // 监听用户切换，当用户切换时刷新组合配置
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId()) }
    
    // 监听用户ID变化，当用户切换时更新currentUserId
    LaunchedEffect(Unit) {
        // 定期检查用户ID是否发生变化
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId()
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 用户切换了，清空查询结果，因为组合配置已经改变
                queryResults = emptyList()
                hasQueriedResults = false
                println("DEBUG: 用户切换检测 - 用户ID从 $currentUserId 切换到 $newUserId")
            }
            delay(1000) // 每秒检查一次
        }
    }
    
    // 无法满足采集点要求的地区状态
    var showInsufficientAreasDialog by remember { mutableStateOf(false) }
    var insufficientAreas by remember { mutableStateOf<List<String>>(emptyList()) }
    
    // 获取当前上下文和设置
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }

    // 动态获取当前启用的标签页列表和对应的区域名称
    val tabsContext = LocalContext.current
    val tabsSettings = remember { com.example.show_auto.data.SettingsStorage(tabsContext) }
    val enableJadeTabs = tabsSettings.getEnableJadeArea()
    val enableVegTabs = tabsSettings.getEnableVegArea()
    val enableCondTabs = false // 强制关闭调料区，因为功能未实现
    val enableLabTabs = tabsSettings.getEnableLabArea()
    
    val enabledAreas = buildList {
        if (enableJadeTabs) add("玉片区")
        if (enableVegTabs) add("菜地区")
        if (enableCondTabs) add("调料区")
        if (enableLabTabs) add("实验室")
    }
    val safeAreas = if (enabledAreas.isEmpty()) listOf("玉片区", "菜地区", "调料区", "实验室") else enabledAreas
    
    // 计算默认选中的标签索引：如果菜地区开启则默认选择菜地区，否则选择第一个启用的区域
    val defaultTabIndex = if (enableVegTabs) {
        safeAreas.indexOf("菜地区").takeIf { it >= 0 } ?: 0
    } else {
        0
    }
    var selectedTabIndex by remember { mutableStateOf(defaultTabIndex) }

    // 按tab过滤结果
    val filteredByTab = remember(queryResults, selectedOption, selectedTabIndex) {
        if (selectedOption == "采集编队") {
            // 采集编队按大区域过滤
            val selectedArea = if (selectedTabIndex < safeAreas.size) safeAreas[selectedTabIndex] else safeAreas.firstOrNull() ?: "菜地区"
            when (selectedArea) {
                "玉片区" -> queryResults.filter { result ->
                    // 玉片区的地点
                    result.area in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
                }
                "菜地区" -> queryResults.filter { result ->
                    // 菜地区的地点
                    result.area in listOf("池塘", "牧场", "猪圈", "鸡舍", "作坊", "菜棚", "菜地", "森林")
                }
                "调料区" -> queryResults.filter { result ->
                    // 调料区的地点（暂时为空，因为调料区功能未实现）
                    result.area.contains("调料区")
                }
                "实验室" -> queryResults.filter { result ->
                    // 实验室的地点
                    result.area in listOf("蒸", "炸", "炒", "煮", "切", "烤")
                }
                else -> queryResults
            }
        } else {
            val area = if (selectedTabIndex < safeAreas.size) safeAreas[selectedTabIndex] else safeAreas.firstOrNull() ?: "菜地区"
            queryResults.filter { it.area == area }
        }
    }

    val countJade = queryResults.count { it.area == "玉片区" }
    val countVeg = queryResults.size // 采集编队显示总数量
    val countCond = queryResults.count { it.area == "调料区" }
    val countLab = queryResults.count { it.area in listOf("蒸", "炸", "炒", "煮", "切", "烤") }



    OppoCompatibilityFix.FixedLayoutContainer(
        modifier = modifier.fillMaxSize()
    ) {
                // 顶部应用栏
        TopAppBar(
            title = { 
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(text = "查询采集编队")
                    Spacer(modifier = Modifier.width(8.dp))
                    IconButton(
                        onClick = { showUsageDialog = true },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = "使用说明",
                            modifier = Modifier.size(20.dp)
                        )
                    }
                }
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(imageVector = Icons.Default.Menu, contentDescription = "菜单")
                }
            },

            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )

        // 页面内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(OppoCompatibilityFix.getFixedSpacing(16.dp)),
            verticalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            // 只有在选择"采集编队"时才显示设置按钮
            if (selectedOption == "采集编队") {
                
            }

            // 区域设置部分
            if (selectedOption == "采集编队") {
                // 四个区域的开关状态
                var enableVeg by remember { mutableStateOf(settings.getEnableVegArea()) }
                var enableJade by remember { mutableStateOf(settings.getEnableJadeArea()) }
                var enableLab by remember { mutableStateOf(settings.getEnableLabArea()) }
                var enableCond by remember { mutableStateOf(false) } // 强制关闭调料区，因为功能未实现
                
                // 选择参与查询厨师弹窗状态
                var showChefSelectionDialog by remember { mutableStateOf(false) }
                
                // 当前选择参与查询厨师页面的勾选状态 - 用于一键查询
                var currentSelectedQueryChefs by remember { mutableStateOf<Set<String>>(emptySet()) }
                
                // 监听个人数据变化，初始化已拥有的厨师
                LaunchedEffect(personalData, gameData?.chefs?.size ?: 0) {
                    val currentPersonalData = personalData
                    val currentGameData = gameData
                    if (currentPersonalData != null && currentGameData != null && currentGameData.chefs.isNotEmpty()) {
                        val ownedChefIds = currentGameData.chefs.filter { chef ->
                            currentPersonalData.chefs[chef.chefId]?.got == true
                        }.map { it.chefId }.toSet()
                        currentSelectedQueryChefs = ownedChefIds
                        println("DEBUG: 查询页面 - 初始化已拥有厨师数量: ${ownedChefIds.size}")
                    } else {
                        currentSelectedQueryChefs = emptySet()
                        println("DEBUG: 查询页面 - 无个人数据或游戏数据，初始化为空")
                    }
                }
                
                // 优先级排序弹窗状态
                var showUnifiedConfig by remember { mutableStateOf(false) }
                
                // 区域配置弹窗状态
                var showVegAreaConfig by remember { mutableStateOf(false) }
                var showJadeAreaConfig by remember { mutableStateOf(false) }
                var showLabAreaConfig by remember { mutableStateOf(false) }
                var showCondAreaConfig by remember { mutableStateOf(false) }
                
                // 查询设置展开/收起状态
                var isAreaSettingsExpanded by remember { mutableStateOf(true) }

                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFF5F5F5)),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(12.dp)
                    ) {
                        // 标题行：查询设置 + 收起展开按钮（整行可点击）
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { isAreaSettingsExpanded = !isAreaSettingsExpanded }
                                .padding(bottom = if (isAreaSettingsExpanded) 8.dp else 0.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "查询设置",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium
                            )
                            
                            Icon(
                                imageVector = if (isAreaSettingsExpanded) {
                                    Icons.Default.KeyboardArrowUp
                                } else {
                                    Icons.Default.KeyboardArrowDown
                                },
                                contentDescription = if (isAreaSettingsExpanded) "收起" else "展开",
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(24.dp)
                            )
                        }
                        
                        // 展开内容
                        if (isAreaSettingsExpanded) {
                        
                            // 第一行：菜地区 + 玉片区
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(bottom = 4.dp),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                            // 菜地区开关
                            Card(
                                modifier = Modifier
                                    .weight(1f)
                                    .height(40.dp),
                                colors = CardDefaults.cardColors(containerColor = Color(0xFFE8F5E8)),
                                shape = RoundedCornerShape(6.dp)
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(4.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text(
                                        text = "菜地区",
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        Box(
                                            modifier = Modifier
                                                .width(56.dp)
                                                .height(28.dp)
                                                .background(
                                                    brush = androidx.compose.ui.graphics.Brush.linearGradient(
                                                        colors = listOf(
                                                            Color.White.copy(alpha = 0.3f),
                                                            Color.White.copy(alpha = 0.1f)
                                                        )
                                                    ),
                                                    shape = RoundedCornerShape(14.dp)
                                                )
                                                .border(
                                                    width = 1.dp,
                                                    color = Color.White.copy(alpha = 0.2f),
                                                    shape = RoundedCornerShape(14.dp)
                                                )
                                                .clickable { showVegAreaConfig = true },
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Text(
                                                text = "配置",
                                                fontSize = 11.sp,
                                                color = Color(0xFF4CAF50),
                                                fontWeight = FontWeight.Medium
                                            )
                                        }
                                        Switch(
                                            checked = enableVeg,
                                            onCheckedChange = {
                                                enableVeg = it
                                                settings.saveEnableVegArea(it)
                                            },
                                            modifier = Modifier.scale(0.7f)
                                        )
                                    }
                                }
                            }
                            
                            Spacer(modifier = Modifier.width(8.dp))
                            
                            // 玉片区开关
                            Card(
                                modifier = Modifier
                                    .weight(1f)
                                    .height(40.dp),
                                colors = CardDefaults.cardColors(containerColor = Color(0xFFFFF3E0)),
                                shape = RoundedCornerShape(6.dp)
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(4.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text(
                                        text = "玉片区",
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        Box(
                                            modifier = Modifier
                                                .width(56.dp)
                                                .height(28.dp)
                                                .background(
                                                    brush = androidx.compose.ui.graphics.Brush.linearGradient(
                                                        colors = listOf(
                                                            Color.White.copy(alpha = 0.3f),
                                                            Color.White.copy(alpha = 0.1f)
                                                        )
                                                    ),
                                                    shape = RoundedCornerShape(14.dp)
                                                )
                                                .border(
                                                    width = 1.dp,
                                                    color = Color.White.copy(alpha = 0.2f),
                                                    shape = RoundedCornerShape(14.dp)
                                                )
                                                .clickable { showJadeAreaConfig = true },
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Text(
                                                text = "配置",
                                                fontSize = 11.sp,
                                                color = Color(0xFFFF9800),
                                                fontWeight = FontWeight.Medium
                                            )
                                        }
                                        Switch(
                                            checked = enableJade,
                                            onCheckedChange = {
                                                enableJade = it
                                                settings.saveEnableJadeArea(it)
                                            },
                                            modifier = Modifier.scale(0.7f)
                                        )
                                    }
                                }
                            }
                        }
                        
                        // 第二行：实验室 + 调料区
                Row(
                    modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceEvenly
                        ) {
                            // 实验室开关
                            Card(
                                modifier = Modifier
                                    .weight(1f)
                                    .height(40.dp),
                                colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                                shape = RoundedCornerShape(6.dp)
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(4.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text(
                                        text = "实验室",
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                                        Box(
                                            modifier = Modifier
                                                .width(56.dp)
                                                .height(28.dp)
                                                .background(
                                                    brush = androidx.compose.ui.graphics.Brush.linearGradient(
                                                        colors = listOf(
                                                            Color.White.copy(alpha = 0.3f),
                                                            Color.White.copy(alpha = 0.1f)
                                                        )
                                                    ),
                                                    shape = RoundedCornerShape(14.dp)
                                                )
                                                .border(
                                                    width = 1.dp,
                                                    color = Color.White.copy(alpha = 0.2f),
                                                    shape = RoundedCornerShape(14.dp)
                                                )
                                                .clickable { showLabAreaConfig = true },
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Text(
                                                text = "配置",
                                                fontSize = 11.sp,
                                                color = Color(0xFF2196F3),
                                                fontWeight = FontWeight.Medium
                                            )
                                        }
                                        Switch(
                                            checked = enableLab,
                                            onCheckedChange = {
                                                enableLab = it
                                                settings.saveEnableLabArea(it)
                                            },
                                            modifier = Modifier.scale(0.7f)
                                        )
                                    }
                                }
                            }
                            
                            Spacer(modifier = Modifier.width(8.dp))
                            
                            // 调料区开关
                            Card(
                        modifier = Modifier
                            .weight(1f)
                            .height(40.dp),
                                colors = CardDefaults.cardColors(containerColor = Color(0xFFF3E5F5)),
                                shape = RoundedCornerShape(6.dp)
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(4.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text(
                                        text = "调料区",
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        Box(
                                            modifier = Modifier
                                                .width(56.dp)
                                                .height(28.dp)
                                                .background(
                                                    brush = androidx.compose.ui.graphics.Brush.linearGradient(
                                                        colors = listOf(
                                                            Color.Gray.copy(alpha = 0.3f), // 改为灰色表示禁用
                                                            Color.Gray.copy(alpha = 0.1f)
                                                        )
                                                    ),
                                                    shape = RoundedCornerShape(14.dp)
                                                )
                                                .border(
                                                    width = 1.dp,
                                                    color = Color.Gray.copy(alpha = 0.2f), // 改为灰色边框
                                                    shape = RoundedCornerShape(14.dp)
                                                ),
                                                // 移除clickable，禁用点击
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Text(
                                                text = "配置",
                                                fontSize = 11.sp,
                                                color = Color.Gray, // 改为灰色文字表示禁用
                                                fontWeight = FontWeight.Medium
                                            )
                                        }
                                        Switch(
                                            checked = false, // 强制关闭状态
                                            onCheckedChange = { /* 禁用点击，功能未实现 */ },
                                            enabled = false, // 禁用开关
                                            modifier = Modifier.scale(0.7f)
                                        )
                                    }
                                }
                            }
                        }
                        
                        // 四个按钮分为两行展示，每行两个按钮
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        // 第一行：选择参与查询厨师 + 优先级排序
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 4.dp),
                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            Button(
                                onClick = { showChefSelectionDialog = true },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        ),
                                shape = RoundedCornerShape(6.dp),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp)
                    ) {
                        Text(
                                    text = "选择参与查询厨师",
                                    fontSize = 11.sp
                        )
                    }
                    
                    Button(
                        onClick = { showUnifiedConfig = true },
                        modifier = Modifier
                            .weight(1f)
                                    .height(32.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        ),
                                shape = RoundedCornerShape(6.dp),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp)
                    ) {
                        Text(
                            text = "优先级排序",
                                    fontSize = 11.sp
                                )
                            }
                        }
                        
                        // 第二行：查看编队 + 一键查询
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            Button(
                                onClick = { showSavedCombinationsDialog = true },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = MaterialTheme.colorScheme.primary,
                                    contentColor = MaterialTheme.colorScheme.onPrimary
                                ),
                                shape = RoundedCornerShape(6.dp),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp)
                            ) {
                                Text(
                                    text = "查看编队",
                                    fontSize = 11.sp
                                )
                            }
                            
                    Button(
                        onClick = {
                        // 执行真实查询
                        if (selectedOption == "采集编队" && gameData != null && uiState.isDataLoaded) {
                            val currentGameData = gameData ?: return@Button // 避免智能转换问题
                            val allResults = mutableListOf<ChefResult>()
                            
                            // 在开始查询前清空之前的无法满足要求的地区记录
                            CollectionTeamCalculator.clearInsufficientAreas()
                            
                            // 获取已保存配置中的所有厨师名单和地区名单，用于过滤
                            val savedCombinations = combinationStorage.getAllCombinations()
                            val savedChefNames = savedCombinations
                                .flatMap { it.chefs.map { chef -> chef.name } }
                                .toSet()
                            val savedAreaNames = savedCombinations
                                .map { it.areaName }
                                .toSet()
                            println("DEBUG: 已保存地区名称: $savedAreaNames")
                            
                            // 创建可变的厨师池，使用当前选择参与查询厨师页面的勾选状态
                            val selectedQueryChefs = if (currentSelectedQueryChefs.isNotEmpty()) {
                                // 使用当前页面的勾选状态
                                currentSelectedQueryChefs.map { chefId ->
                                    gameData?.chefs?.find { it.chefId == chefId }?.name ?: ""
                                }.filter { it.isNotEmpty() }.toSet()
                            } else {
                                // 如果没有当前勾选状态，则使用持久化存储的数据（兼容旧逻辑）
                                settings.getSelectedQueryChefs()
                            }
                            val currentPersonalData = personalData // 创建局部变量避免委托属性问题
                            

                            

                            
                            val availableChefs = if (settings.getCalculatorUseAllChefs()) {
                                // 如果开启"使用全部厨师"，使用所有厨师（优先级最高）
                                val allChefs = currentGameData.chefs.filter { chef ->
                                    chef.name !in savedChefNames
                                }.toMutableList()
                                println("DEBUG: 一键查询 - 使用全部厨师模式，可用厨师数量: ${allChefs.size}")
                                allChefs
                            } else if (selectedQueryChefs.isNotEmpty()) {
                                // 使用用户选择的厨师，但排除已保存配置中的厨师
                                currentGameData.chefs.filter { chef ->
                                    chef.name in selectedQueryChefs && chef.name !in savedChefNames
                                }.toMutableList()
                            } else {
                                // 如果没有选择，则使用所有已拥有厨师（兼容旧逻辑）
                                if (currentPersonalData != null) {
                                    val ownedChefs = currentGameData.chefs.filter { chef ->
                                        chef.name !in savedChefNames && 
                                        currentPersonalData.chefs[chef.chefId]?.got == true
                                    }.toMutableList()
                                    println("DEBUG: 一键查询 - 筛选后可用厨师数量: ${ownedChefs.size}")
                                    ownedChefs
                                } else {
                                    val allChefs = currentGameData.chefs.filter { chef ->
                                        chef.name !in savedChefNames
                                    }.toMutableList()
                                    println("DEBUG: 一键查询 - 无个人数据，使用所有厨师: ${allChefs.size}")
                                    allChefs
                                }
                            }
                            
                            // 过滤掉已保存的地区配置，避免计算已保存地区的结果
                            val filteredVegConfigs = if (settings.getEnableVegArea()) {
                                (getUnifiedAreaConfigs(settings, "veg") as List<VegAreaItem>).filter { config ->
                                    config.name !in savedAreaNames
                                }
                            } else emptyList()
                            
                            val filteredJadeConfigs = if (settings.getEnableJadeArea()) {
                                (getUnifiedAreaConfigs(settings, "jade") as List<JadeAreaItem>).filter { config ->
                                    config.name !in savedAreaNames
                                }
                            } else emptyList()
                            
                            val filteredLabConfigs = if (settings.getEnableLabArea()) {
                                val allLabConfigs = getUnifiedAreaConfigs(settings, "lab") as List<LabItem>
                                println("DEBUG: 所有实验室配置: ${allLabConfigs.map { it.name }}")
                                val filtered = allLabConfigs.filter { config ->
                                    val shouldExclude = config.name in savedAreaNames
                                    println("DEBUG: 实验室配置 ${config.name} - 是否已保存: $shouldExclude")
                                    !shouldExclude
                                }
                                println("DEBUG: 过滤后实验室配置: ${filtered.map { it.name }}")
                                filtered
                            } else emptyList()
                            
                            // 按混合配置的具体地区顺序执行查询，确保前边地区使用过的厨师不会在后续地区中再使用
                            
                                                        // 获取统一排序的具体地区顺序（已在设置保存时自动清理）
                            val unifiedOrder = settings.getUnifiedAreaOrder()
                            println("DEBUG: 一键查询 - 获取到的统一排序: $unifiedOrder")
                            
                            // 检查统一排序的完整性
                            val hasVegAreas = unifiedOrder.any { it.startsWith("veg_") }
                            val hasJadeAreas = unifiedOrder.any { it.startsWith("jade_") }
                            val hasCondAreas = unifiedOrder.any { it.startsWith("cond_") }
                            val hasLabAreas = unifiedOrder.any { it.startsWith("lab_") }
                            println("DEBUG: 一键查询 - 统一排序包含: 菜地区=$hasVegAreas, 玉片区=$hasJadeAreas, 调料区=$hasCondAreas, 实验室=$hasLabAreas")
                            
                            if (unifiedOrder.isNotEmpty()) {
                                // 根据区域开关状态过滤已启用的地区
                                val allEnabledAreas = mutableListOf<String>()
                                
                                // 检查菜地区开关
                                if (settings.getEnableVegArea()) {
                                    val vegConfigs = getVegAreaConfigs(settings)
                                    val enabledVegAreas = vegConfigs.filter { it.currentPeople > 0 && it.name !in savedAreaNames }.map { "veg_${it.name}" }
                                    allEnabledAreas.addAll(enabledVegAreas)
                                }
                                
                                // 检查玉片区开关  
                                if (settings.getEnableJadeArea()) {
                                    val jadeConfigs = getJadeAreaConfigs(settings)
                                    val enabledJadeAreas = jadeConfigs.filter { it.currentPeople > 0 && it.name !in savedAreaNames }.map { "jade_${it.name}" }
                                    allEnabledAreas.addAll(enabledJadeAreas)
                                    println("DEBUG: 一键查询 - 玉片区已启用，包含地区: $enabledJadeAreas")
                                } else {
                                    println("DEBUG: 一键查询 - 玉片区已关闭")
                                }
                                
                                // 检查调料区开关 - 使用UI状态而非设置值，因为功能未实现
                                if (enableCond) {
                                    val condConfigs = getCondAreaConfigs(settings)
                                    val enabledCondAreas = condConfigs.filter { it.currentPeople > 0 && it.name !in savedAreaNames }.map { "cond_${it.name}" }
                                    allEnabledAreas.addAll(enabledCondAreas)
                                    println("DEBUG: 一键查询 - 调料区已启用，包含地区: $enabledCondAreas")
                                } else {
                                    println("DEBUG: 一键查询 - 调料区已关闭")
                                }
                                
                                // 检查实验室开关
                                if (settings.getEnableLabArea()) {
                                    val labConfigs = getLabAreaConfigs(settings)
                                    val enabledLabAreas = labConfigs.filter { it.currentPeople > 0 && it.name !in savedAreaNames }.map { "lab_${it.name}" }
                                    allEnabledAreas.addAll(enabledLabAreas)
                                    println("DEBUG: 一键查询 - 实验室已启用，包含地区: $enabledLabAreas")
                                } else {
                                    println("DEBUG: 一键查询 - 实验室已关闭")
                                }
                                
                                println("DEBUG: 一键查询 - 最终所有已启用地区: $allEnabledAreas")
                                
                                // 检查是否有已启用的地区不在统一排序中，如果有则添加
                                val missingFromUnified = allEnabledAreas.filter { it !in unifiedOrder }
                                val finalUnifiedOrder = if (missingFromUnified.isNotEmpty()) {
                                    val updatedOrder = unifiedOrder + missingFromUnified
                                    settings.saveUnifiedAreaOrder(updatedOrder)
                                    println("DEBUG: 一键查询 - 发现缺失地区，自动添加到统一排序")
                                    println("DEBUG: 一键查询 - 缺失地区: $missingFromUnified")
                                    println("DEBUG: 一键查询 - 更新后统一排序: $updatedOrder")
                                    updatedOrder
                                } else {
                                    println("DEBUG: 一键查询 - 统一排序完整，无需添加")
                                    unifiedOrder
                                }
                                
                                // 按统一排序逐个地区分配，但只处理已启用的地区
                                finalUnifiedOrder.forEach { itemId ->
                                    // 检查是否是已保存的地区
                                    val isAreaSaved = when {
                                        itemId.startsWith("lab_") -> {
                                            val areaName = itemId.removePrefix("lab_")
                                            areaName in savedAreaNames // 实验室检查技法名称
                                        }
                                        else -> itemId in savedAreaNames // 其他地区直接检查
                                    }
                                    
                                    println("DEBUG: 检查地区 $itemId - 是否已保存: $isAreaSaved, 是否启用: ${itemId in allEnabledAreas}")
                                    
                                    if (!isAreaSaved && itemId in allEnabledAreas) { // 跳过已保存的地区和未启用的地区
                                        println("DEBUG: 一键查询 - 处理地区: $itemId")
                                        when {
                                            itemId.startsWith("veg_") -> {
                                                val areaName = itemId.removePrefix("veg_")
                                                processVegAreaSingle(areaName, currentGameData, availableChefs, personalData, settings, allResults)
                                            }
                                            itemId.startsWith("jade_") -> {
                                                val areaName = itemId.removePrefix("jade_")
                                                val jadeSilverShoesEnabled = settings.getUseJadeSilverShoes()
                                                val jadeUseMaxLevelAmber = settings.getUseJadeMaxLevelAmber()
                                                processJadeAreaSingle(areaName, currentGameData, availableChefs, personalData, settings, allResults, jadeSilverShoesEnabled, jadeUseMaxLevelAmber)
                                            }
                                            itemId.startsWith("lab_") -> {
                                                val areaName = itemId.removePrefix("lab_")
                                                processLabAreaSingle(areaName, currentGameData, availableChefs, personalData, settings, allResults, context)
                                            }
                                            itemId.startsWith("cond_") -> {
                                                val areaName = itemId.removePrefix("cond_")
                                                processCondAreaSingle(areaName, currentGameData, availableChefs, personalData, settings, allResults)
                                            }
                                        }
                                    }
                                }
                            } else {
                                // 回退到旧的按区域类型分组的查询逻辑
                                val allEnabledAreas = getDynamicQueryOrder(settings)
                                println("DEBUG: 一键查询 - 回退到区域分组查询，启用的区域顺序: $allEnabledAreas")
                                
                                allEnabledAreas.forEach { areaType ->
                                    println("DEBUG: 一键查询 - 处理区域类型: $areaType")
                                    when (areaType) {
                                    "菜地区" -> {
                                        if (settings.getEnableVegArea() && filteredVegConfigs.isNotEmpty()) {
                                            val silverShoesEnabled = settings.getUseSilverShoes()
                                            val useMaxLevelAmber = settings.getUseMaxLevelAmber()
      
                                            println("DEBUG: 菜地区查询 - 可用厨师数量: ${availableChefs.size}")
                                            println("DEBUG: 菜地区查询 - 个人数据状态: ${if (personalData != null) "已加载" else "未加载"}")
      
                                            val vegResults = CollectionTeamCalculator.calculateVegAreaResults(
                                                gameData = currentGameData.copy(chefs = availableChefs),
                                                personalData = personalData,
                                                vegEnabled = true,
                                                vegAreaConfigs = filteredVegConfigs,
                                                useSilverShoes = silverShoesEnabled,
                                                useMaxLevelAmber = useMaxLevelAmber,
                                                useAllUltimateTraining = settings.getUseAllUltimateTraining(),
                                                useAllChefs = settings.getCalculatorUseAllChefs()
                                            ).map { result ->
                                                // 查找对应的厨师数据计算技能信息
                                                val chef = availableChefs.find { it.name == result.chefName }
                                                if (chef != null) {
                                                    // 根据地区名称确定采集类型
                                                    val targetType = when (result.area) {
                                                        "池塘" -> "鱼"
                                                        "牧场", "猪圈", "鸡舍" -> "肉"
                                                        "菜棚", "菜地", "森林" -> "菜"
                                                        "作坊" -> "面"
                                                        else -> ""
                                                    }
                                                                                                  val separatedSkills = CollectionTeamCalculator.calculateSeparatedSkillBonus(
                                                  chef, currentGameData, personalData, targetType, silverShoesEnabled, useMaxLevelAmber, false, settings.getUseAllUltimateTraining()
                                              )
                                                    val chefResult = ChefResultWithSkills(
                                                        chefName = result.chefName,
                                                        chefRarity = result.rarity,
                                                        chefTimeSeconds = result.timeEfficiency,
                                                        chefOwned = result.owned,
                                                        chefArea = result.area,
                                                        chefCollectionDetails = "肉:${result.collectionStats.meat} 鱼:${result.collectionStats.fish} 菜:${result.collectionStats.veg} 面:${result.collectionStats.creation}",
                                                        chefIsUltimate = chef.ult,
                                                        critChance = separatedSkills.totalCritChance,
                                                        critMaterial = separatedSkills.totalCritMaterial,
                                                        materialGain = separatedSkills.totalMaterialGain,
                                                        // 基础采集点（厨师原始数据）
                                                        baseMeat = chef.meat,
                                                        baseFish = chef.fish,
                                                        baseVeg = chef.veg,
                                                        baseCreation = chef.creation,
                                                        // 加成后采集点（计算结果）
                                                        totalMeat = result.collectionStats.meat,
                                                        totalFish = result.collectionStats.fish,
                                                        totalVeg = result.collectionStats.veg,
                                                        totalCreation = result.collectionStats.creation
                                                    )
                                                    
                                                    // 从可用厨师池中移除已使用的厨师
                                                    availableChefs.removeAll { it.name == result.chefName }
                                                    
                                                    chefResult
                                                } else {
                                                    ChefResult(
                                                        name = result.chefName,
                                                        rarity = result.rarity,
                                                        timeSeconds = result.timeEfficiency,
                                                        owned = result.owned,
                                                        area = result.area,
                                                        collectionDetails = "肉:${result.collectionStats.meat} 鱼:${result.collectionStats.fish} 菜:${result.collectionStats.veg} 面:${result.collectionStats.creation}",
                                                        isUltimate = false
                                                    )
                                                }
                                            }
                                            allResults.addAll(vegResults)
                                        }
                                    }
                                    "玉片区" -> {

                                        if (settings.getEnableJadeArea() && filteredJadeConfigs.isNotEmpty()) {
                                            val jadeSilverShoesEnabled = settings.getUseJadeSilverShoes()
                                            val jadeUseMaxLevelAmber = settings.getUseJadeMaxLevelAmber()
  
                                            println("DEBUG: 玉片区查询 - 可用厨师数量: ${availableChefs.size}")
                                            println("DEBUG: 玉片区查询 - 个人数据状态: ${if (personalData != null) "已加载" else "未加载"}")
  
                                            val jadeResults = CollectionTeamCalculator.calculateJadeAreaResults(
                                                gameData = currentGameData.copy(chefs = availableChefs),
                                                personalData = personalData,
                                                jadeEnabled = true,
                                                jadeAreaConfigs = filteredJadeConfigs,
                                                useSilverShoes = jadeSilverShoesEnabled,
                                                useMaxLevelAmber = jadeUseMaxLevelAmber,
                                                useAllUltimateTraining = settings.getUseAllUltimateTraining(),
                                                useAllChefs = settings.getCalculatorUseAllChefs()
                                            ).map { result ->
                                                // 查找对应的厨师数据计算技能信息
                                                val chef = availableChefs.find { it.name == result.chefName }
                                                if (chef != null) {
                                                    // 根据地区名称确定采集类型和双类型采集点信息
                                                    val (targetType, dualTypeInfo) = when (result.area) {
                                                        "藏心亭" -> "肉" to "肉+菜:${result.totalCapacity}"
                                                        "朝阴山" -> "肉" to "肉+面:${result.totalCapacity}"
                                                        "北冥城" -> "鱼" to "鱼+面:${result.totalCapacity}"
                                                        "清空谷" -> "肉" to "肉+鱼:${result.totalCapacity}"
                                                        "还寒洞" -> "菜" to "菜+面:${result.totalCapacity}"
                                                        "永昼宫" -> "菜" to "菜+鱼:${result.totalCapacity}"
                                                        else -> "" to ""
                                                    }
                                                    
                                                    val separatedSkills = CollectionTeamCalculator.calculateSeparatedSkillBonus(
                                                        chef, currentGameData, personalData, targetType, jadeSilverShoesEnabled, jadeUseMaxLevelAmber, true, settings.getUseAllUltimateTraining()
                                                    )
                                                    val chefResult = ChefResultWithSkills(
                                                        chefName = result.chefName,
                                                        chefRarity = result.rarity,
                                                        chefTimeSeconds = result.timeEfficiency,
                                                        chefOwned = result.owned,
                                                        chefArea = result.area,
                                                        chefCollectionDetails = dualTypeInfo,
                                                        chefIsUltimate = chef.ult,
                                                        critChance = separatedSkills.totalCritChance,
                                                        critMaterial = separatedSkills.totalCritMaterial,
                                                        materialGain = separatedSkills.totalMaterialGain,
                                                        // 基础采集点（厨师原始数据）
                                                        baseMeat = chef.meat,
                                                        baseFish = chef.fish,
                                                        baseVeg = chef.veg,
                                                        baseCreation = chef.creation,
                                                        // 加成后采集点（计算结果）
                                                        totalMeat = result.collectionStats.meat,
                                                        totalFish = result.collectionStats.fish,
                                                        totalVeg = result.collectionStats.veg,
                                                        totalCreation = result.collectionStats.creation
                                                    )
                                                    
                                                    // 从可用厨师池中移除已使用的厨师
                                                    availableChefs.removeAll { it.name == result.chefName }
                                                    
                                                    chefResult
                                                } else {
                                                    ChefResult(
                                                        name = result.chefName,
                                                        rarity = result.rarity,
                                                        timeSeconds = result.timeEfficiency,
                                                        owned = result.owned,
                                                        area = result.area,
                                                        collectionDetails = "双类型采集点:${result.totalCapacity}",
                                                        isUltimate = false
                                                    )
                                                }
                                            }
                                            allResults.addAll(jadeResults)
                                        }
                                    }
                                    "调料区" -> {
                                        if (enableCond) {
                                            val condResults = listOf(
                                                ChefResult(
                                                    name = "调料区功能开发中",
                                                    rarity = 1,
                                                    timeSeconds = 0,
                                                    owned = false,
                                                    area = "调料区",
                                                    collectionDetails = "功能开发中，敬请期待",
                                                    isUltimate = false
                                                )
                                            )
                                            allResults.addAll(condResults)
                                        }
                                    }
                                    "实验室" -> {
                                        println("DEBUG: 进入实验室查询分支")
                                        if (settings.getEnableLabArea()) {
                                            println("DEBUG: 实验室已启用")
                                            val labConfigs = getLabAreaConfigs(settings).filter { it.currentPeople > 0 }
                                            println("DEBUG: 实验室配置数量: ${labConfigs.size}")
                                            
                                            // 获取实验室配置开关
        val useLabEquip150 = settings.getUseLabEquip150()
        val useBeginnerEquip100 = settings.getUseBeginnerEquip100()
        val useMaxLevelAmber = settings.getUseMaxLevelAmber()
                                            val useAllChefs = settings.getCalculatorUseAllChefs()
                                            
                                            // 获取已分配厨师ID和已保存组合厨师ID
                                            val excludedChefIds = allResults.map { result ->
                                                currentGameData.chefs.find { it.name == result.name }?.chefId ?: ""
                                            }.filter { it.isNotEmpty() }.toSet()
                                            
                                            val combinationStorage = CombinationStorage(context)
                                            val savedCombinationChefIds = combinationStorage.getAllCombinations()
                                                .flatMap { combination ->
                                                    combination.chefs.map { chef ->
                                                        currentGameData.chefs.find { it.name == chef.name }?.chefId ?: ""
                                                    }
                                                }.filter { it.isNotEmpty() }.toSet()
                                            
                                            // 从当前个人数据中识别并保存光环厨师
                                            val personalDataManager = PersonalDataManager(context)
                                            
                                            // 识别当前游戏数据中的所有光环厨师
                                            val allAuraChefs = currentGameData.chefs.filter { chef ->
                                                isAuraChef(chef, currentGameData.skills)
                                            }
                                            println("DEBUG: 游戏数据中光环厨师总数: ${allAuraChefs.size}")
                                            if (allAuraChefs.isNotEmpty()) {
                                                println("DEBUG: 光环厨师列表: ${allAuraChefs.map { it.name }}")
                                            }
                                            
                                            val useAllUltimateTraining = settings.getUseAllUltimateTraining()
                                            val currentPersonalData = personalData // 创建局部变量避免委托属性问题
                                            println("DEBUG: 全修炼开关: $useAllUltimateTraining")
                                            println("DEBUG: 个人数据是否存在: ${currentPersonalData != null}")
                                            
                                            // 根据当前用户的拥有和修炼状态，确定启用的光环厨师
                                            val enabledAuraChefNames = if (currentPersonalData != null) {
                                                val filteredAuraChefs = allAuraChefs.filter { chef ->
                                                    val isOwned = currentPersonalData.chefs[chef.chefId]?.got == true
                                                    val isUltimate = chef.ult
                                                    println("DEBUG: ${chef.name} - 拥有:$isOwned, 修炼:$isUltimate")
                                                    
                                                    if (isOwned) {
                                                        if (useAllUltimateTraining) {
                                                            true // 开启全修炼开关，已拥有的光环厨师都启用
                                                        } else {
                                                            isUltimate // 未开启全修炼，只启用已修炼的光环厨师
                                                        }
                                                    } else {
                                                        false
                                                    }
                                                }
                                                val result = filteredAuraChefs.map { it.name }.toSet()
                                                println("DEBUG: 启用的光环厨师: $result")
                                                result
                                            } else {
                                                // 没有个人数据时，根据全修炼开关决定
                                                val result = if (useAllUltimateTraining) {
                                                    allAuraChefs.map { it.name }.toSet()
                                                } else {
                                                    allAuraChefs.filter { it.ult }.map { it.name }.toSet()
                                                }
                                                println("DEBUG: 无个人数据时启用的光环厨师: $result")
                                                result
                                            }
                                            
                                            // 保存当前启用的光环厨师到用户数据
                                            personalDataManager.saveUserAuraChefs(enabledAuraChefNames)
                                            println("DEBUG: 保存到个人数据的光环厨师: $enabledAuraChefNames")
                                            
                                            val enabledAuraChefs = enabledAuraChefNames
                                            
                     
                                            

                                            
                                            // 逐个技法计算实验室结果，避免厨师重复分配
                                            val labResults = mutableListOf<ChefResult>()
                                            
                                            labConfigs.forEach { labConfig ->
                                                // 每个技法单独计算
                                                val singleResults = CollectionTeamCalculator.calculateLabAreaResults(
                                                    gameData = currentGameData.copy(chefs = availableChefs),
                                                    personalData = personalData,
                                                    labEnabled = true,
                                                    labAreaConfigs = listOf(labConfig), // 只传入当前技法配置
                                                    useLabEquip150 = useLabEquip150,
                                                    useBeginnerEquip100 = useBeginnerEquip100,
                                                    useMaxLevelAmber = useMaxLevelAmber,
                                                    useAllChefs = useAllChefs,
                                                    excludedChefIds = excludedChefIds,
                                                    savedCombinationChefIds = savedCombinationChefIds,
                                                    enabledAuraChefs = enabledAuraChefs,
                                                    context = context,
                                                    useAllUltimateTraining = settings.getUseAllUltimateTraining()
                                                ).map { result ->
                                                    // 转换为ChefResult格式
                                                    val chef = availableChefs.find { it.name == result.chefName }
                                                    if (chef != null) {
                                                        // 从可用厨师中移除已分配的厨师
                                                        availableChefs.removeAll { it.chefId == chef.chefId }
                                                        
                                                        // 构建详细信息，实验室显示总技法值
                                                        val detailsBuilder = StringBuilder()
                                                        detailsBuilder.append("${result.area}技法值: ${result.skillValue}")
                                                        
                                                        // 如果是光环厨师，添加光环信息
                                                        if (result.isAuraChef) {
                                                            // 从游戏数据中获取光环加成值
                                                            val chef = currentGameData.chefs.find { it.name == result.chefName }
                                                            if (chef != null) {
                                                                // 检查该厨师是否在当前用户的光环厨师配置中
                                                                if (chef.name in enabledAuraChefs) {
                                                                    // 获取光环技能加成值和类型
                                                                    val (auraBonus, auraType) = getChefAuraBonusWithType(chef, currentGameData.skills, result.area)
                                                                    if (auraBonus > 0) {
                                                                        // 根据光环类型决定乘数
                                                                        val (multiplier, multiplierDesc) = when (auraType) {
                                                                            "下位上场厨师" -> Pair(1, "X1")
                                                                            "场上所有厨师" -> {
                                                                                val peopleCount = labConfig.currentPeople
                                                                                Pair(peopleCount, "X$peopleCount")
                                                                            }
                                                                            else -> Pair(1, "X1")
                                                                        }
                                                                        val totalAuraBonus = auraBonus * multiplier
                                                                        detailsBuilder.append("（光环：${result.area}+${auraBonus} ${multiplierDesc} = ${totalAuraBonus}）")
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        
                                                    ChefResult(
                                                            name = result.chefName,
                                                            rarity = result.rarity,
                                                            timeSeconds = 0, // 实验室不使用时间效率
                                                            owned = result.owned,
                                                            area = result.area,
                                                            collectionDetails = detailsBuilder.toString(),
                                                            isUltimate = chef.ult // 使用厨师的真实修炼状态
                                                    )
                                                    } else null
                                                }.filterNotNull()
                                                
                                                labResults.addAll(singleResults)
                                            }
                                            
                                            allResults.addAll(labResults)
                                        }
                                    }
                                    }
                                }
                            }

                            
                            queryResults = allResults
                            hasQueriedResults = true
                            queryCounter++ // 增加查询计数器，强制刷新展开状态
                                         
                                         // 查询完成后自动收起查询设置
                                         isAreaSettingsExpanded = false
                            
                            // 强制刷新所有启用地区的展开状态
                            // 这将在下次UI重组时生效
                            
                            // 检查是否有无法满足采集点要求的地区
                            val insufficientAreasList = CollectionTeamCalculator.getInsufficientAreas()
                            if (insufficientAreasList.isNotEmpty()) {
                                insufficientAreas = insufficientAreasList
                                showInsufficientAreasDialog = true
                            }
                            
                            // 自动选择标签页：如果菜地区开启则选择菜地区，否则选择第一个启用的标签页
                            if (safeAreas.isNotEmpty()) {
                                selectedTabIndex = if (enableVegTabs) {
                                    safeAreas.indexOf("菜地区").takeIf { it >= 0 } ?: 0
                                } else {
                                    0
                                }
                            }
                        }
                        },
                        modifier = Modifier
                            .weight(1f)
                                    .height(32.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        ),
                                shape = RoundedCornerShape(6.dp),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp),
                        enabled = selectedOption != null && gameData != null && uiState.isDataLoaded
                    ) {
                                Text("一键查询", fontSize = 11.sp)
                            }
                        }
                        }
                    }
                }
                
                // 区域配置弹窗
                if (showVegAreaConfig) NewVegAreaConfigDialog(onDismiss = { showVegAreaConfig = false })
                if (showJadeAreaConfig) NewJadeAreaConfigDialog(onDismiss = { showJadeAreaConfig = false })
                if (showLabAreaConfig) NewLabAreaConfigDialog(onDismiss = { showLabAreaConfig = false })
                if (showCondAreaConfig) NewCondAreaConfigDialog(onDismiss = { showCondAreaConfig = false })
                
                // 厨师选择弹窗
                if (showChefSelectionDialog) {
                    ChefSelectionDialog(
                        onDismiss = { showChefSelectionDialog = false },
                        onSelectionChanged = { selectedChefIds ->
                            currentSelectedQueryChefs = selectedChefIds
                        }
                    )
                }
                
                // 优先级排序弹窗
                if (showUnifiedConfig) {
                    UnifiedQuerySortingDialog(onDismiss = { showUnifiedConfig = false })
                }
                
                Spacer(modifier = Modifier.height(8.dp))
            }

            
            // 显示已保存组合配置弹窗
            if (showSavedCombinationsDialog) {
                SavedCombinationsDialog(
                    combinationStorage = combinationStorage,
                    onSelectCombination = { combination ->
                        selectedCombination = combination
                        showSavedCombinationsDialog = false
                        showCombinationDetailsDialog = true
                    },
                    onDismiss = { showSavedCombinationsDialog = false },
                    onReturnFromSchemeLoad = { 
                        // 从方案加载后返回到已保存组合配置页面并刷新数据
                        combinationsRefreshTrigger++
                        showSavedCombinationsDialog = true
                    },
                    refreshTrigger = combinationsRefreshTrigger
                )
            }
            
            // 显示组合详情弹窗
            if (showCombinationDetailsDialog && selectedCombination != null) {
                CombinationDetailsDialog(
                    combination = selectedCombination!!,
                    onDismiss = { 
                        showCombinationDetailsDialog = false
                        selectedCombination = null
                        showSavedCombinationsDialog = true // 返回到已保存配置弹窗
                    }
                )
            }
            
            // 显示保存成功弹窗
            if (showSaveSuccessDialog) {
                SaveSuccessDialog(
                    onDismiss = { showSaveSuccessDialog = false }
                )
            }
            
            // 显示无法满足采集点要求的地区弹窗
            if (showInsufficientAreasDialog) {
                InsufficientAreasDialog(
                    insufficientAreas = insufficientAreas,
                    onDismiss = { showInsufficientAreasDialog = false }
                )
            }
            
            // 显示使用说明弹窗
            if (showUsageDialog) {
                ComprehensiveQueryUsageDialog(
                    onDismiss = { showUsageDialog = false }
                )
            }
            
            // 显示替换厨师弹窗
            if (showReplaceDialog && gameData != null) {
                ReplaceChefDialog(
                    areaName = replaceAreaName,
                    currentChefName = replaceChefName,
                    gameData = gameData!!,
                    personalData = personalData,
                    combinationStorage = combinationStorage,
                    currentQueryResults = queryResults,
                    onDismiss = { showReplaceDialog = false },
                    onReplaceChef = { newChef ->
                        // 检查新厨师是否已被分配到其他地区
                        val originalArea = queryResults.find { it.name == newChef.name }?.area
                        
                        if (replaceChefName.isEmpty()) {
                            // 添加新厨师逻辑（当replaceChefName为空时）
                            val updatedResults = queryResults.toMutableList()
                            
                            // 如果新厨师原本在其他地区，从原地区移除
                            if (originalArea != null) {
                                updatedResults.removeAll { result ->
                                    result.name == newChef.name && result.area == originalArea
                                }
                            }
                            
                            // 添加新厨师到目标地区
                            val newChefWithArea = if (newChef is ChefResultWithSkills) {
                                newChef.copy(chefArea = replaceAreaName)
                            } else {
                                newChef
                            }
                            updatedResults.add(newChefWithArea)
                            
                            queryResults = updatedResults
                        } else {
                            // 替换厨师逻辑（原有逻辑）
                            val updatedResults = queryResults.mapNotNull { result ->
                                when {
                                    // 如果是要替换的厨师，更换为新厨师
                                    result.area == replaceAreaName && result.name == replaceChefName -> {
                                        // newChef是ChefResultWithSkills类型，更新地区
                                        if (newChef is ChefResultWithSkills) {
                                            newChef.copy(chefArea = replaceAreaName)
                                        } else {
                                            newChef // 这种情况应该不会发生
                                        }
                                    }
                                    // 如果新厨师原本在其他地区，从原地区移除
                                    originalArea != null && result.name == newChef.name && result.area == originalArea -> {
                                        null
                                    }
                                    // 其他厨师保持不变
                                    else -> result
                                }
                            }
                            
                            queryResults = updatedResults
                        }
                        
                        // 如果是玉片区的替换，需要重新计算全场加成
                        if (replaceAreaName in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")) {
                            // 先更新新厨师的显示格式为双类型采集点总和
                            queryResults = updateNewChefDisplayFormat(queryResults, replaceAreaName, newChef, gameData!!)
                            // 然后重新计算全场加成
                            queryResults = recalculateJadeAreaWithGlobalBonus(
                                queryResults, 
                                replaceAreaName, 
                                replaceChefName, 
                                newChef, 
                                gameData!!,
                                personalData,
                                settings.getUseAllUltimateTraining()
                            )
                        }
                        // 如果是菜地区的替换，也需要重新计算全场加成
                        else if (replaceAreaName in listOf("池塘", "牧场", "猪圈", "鸡舍", "作坊", "菜棚", "菜地", "森林")) {
                            // 重新计算菜地区全场加成
                            queryResults = recalculateVegAreaWithGlobalBonus(
                                queryResults, 
                                replaceAreaName, 
                                replaceChefName, 
                                newChef, 
                                gameData!!,
                                personalData,
                                settings.getUseAllUltimateTraining()
                            )
                        }
                        // 如果是实验室区的替换，需要重新计算实验室总技法值
                        else if (replaceAreaName in listOf("蒸", "炸", "炒", "煮", "切", "烤")) {
                            // 重新计算实验室区域的总技法值
                            queryResults = recalculateLabAreaTotalSkill(
                                queryResults,
                                replaceAreaName,
                                gameData!!,
                                personalData,
                                settings,
                                context
                            )
                        }
                        
                        showReplaceDialog = false
                    }
                )
            }



            // 结果展示
            if (hasQueriedResults) {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = Color(0xFFE8E8E8),
                    shape = androidx.compose.foundation.shape.RoundedCornerShape(8.dp)
                ) {
                    Column(modifier = Modifier.padding(16.dp)) {


                        // 三段切换：玉片区 / 菜地区 / 调料区（胶囊式）
                        if (true) { // 所有查询类型都显示tab切换
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 16.dp),
                                shape = androidx.compose.foundation.shape.RoundedCornerShape(20.dp),
                                colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                            ) {
                            Row(modifier = Modifier.padding(4.dp)) {
                                // 根据开关筛选要展示的tab
                                val allTabs = listOf(
                                    "玉片区" to countJade,
                                    "菜地区" to countVeg,
                                    "调料区" to countCond,
                                    "实验室" to countLab
                                )
                                // 使用已经获取的开关状态
                                val enabledFlags = listOf(enableJadeTabs, enableVegTabs, enableCondTabs, enableLabTabs)
                                val shownTabs = allTabs.filterIndexed { index, _ -> enabledFlags[index] }
                                val safeTabs = if (shownTabs.isEmpty()) allTabs else shownTabs
                                if (selectedTabIndex >= safeTabs.size) {
                                    selectedTabIndex = 0
                                }
                                safeTabs.forEachIndexed { index, pair ->
                                    val selected = selectedTabIndex == index
                                    Surface(
                                        onClick = { selectedTabIndex = index },
                                        modifier = Modifier
                                            .weight(1f)
                                            .height(28.dp),
                                        shape = androidx.compose.foundation.shape.RoundedCornerShape(16.dp),
                                        color = if (selected) MaterialTheme.colorScheme.primary else Color.Transparent
                                    ) {
                                        Box(
                                            modifier = Modifier.fillMaxSize(),
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Text(
                                                text = pair.first,
                                                fontSize = 12.sp,
                                                fontWeight = FontWeight.Medium,
                                                color = if (selected) Color.White else MaterialTheme.colorScheme.primary
                                            )
                                        }
                                    }
                                    if (index < safeTabs.lastIndex) Spacer(modifier = Modifier.width(4.dp))
                                }
                            }
                        }
                        }

                        Spacer(modifier = Modifier.height(8.dp))

                        // 列表
                        if (filteredByTab.isEmpty()) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                    Icon(
                                        imageVector = Icons.Default.Search,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                        modifier = Modifier.size(48.dp)
                                    )
                                    Spacer(modifier = Modifier.height(8.dp))
                                    Text(
                                        text = "暂无相关结果",
                                        fontSize = 16.sp,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        } else {
                            if (selectedOption == "采集编队") {
                                // 采集编队按地点分组显示
                                val groupedResults = filteredByTab.groupBy { it.area }
                                // 每个地区的展开状态 - 确保每次查询后都默认展开
                                val expandedStates = remember(queryResults, queryCounter, selectedTabIndex, enableJadeTabs, enableVegTabs, enableCondTabs, enableLabTabs) { 
                                    mutableStateMapOf<String, Boolean>().apply {
                                        // 每次查询完成后，重置所有地区为展开状态
                                        // 包括当前标签页和所有启用的标签页下的地区
                                        val allEnabledAreas = mutableSetOf<String>()
                                        
                                        // 添加当前标签页的地区
                                        groupedResults.keys.forEach { areaName ->
                                            allEnabledAreas.add(areaName)
                                        }
                                        
                                        // 添加其他启用标签页下的地区（确保切换标签页时保持展开状态）
                                        if (enableJadeTabs) {
                                            listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫").forEach { areaName ->
                                                allEnabledAreas.add(areaName)
                                            }
                                        }
                                        if (enableVegTabs) {
                                            listOf("池塘", "牧场", "猪圈", "鸡舍", "作坊", "菜棚", "菜地", "森林").forEach { areaName ->
                                                allEnabledAreas.add(areaName)
                                            }
                                        }
                                        if (enableCondTabs) {
                                            listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁").forEach { areaName ->
                                                allEnabledAreas.add(areaName)
                                            }
                                        }
                                        if (enableLabTabs) {
                                            listOf("蒸", "炸", "炒", "煮", "切", "烤").forEach { areaName ->
                                                allEnabledAreas.add(areaName)
                                            }
                                        }
                                        
                                        // 设置所有启用地区为展开状态
                                        allEnabledAreas.forEach { areaName ->
                                            this[areaName] = true // 默认展开
                                        }
                                    }
                                }
                                
                                LazyColumn {
                                    groupedResults.forEach { (areaName, chefs) ->
                                        item {
                                            // 整个地区的Card容器
                                            Card(
                                                modifier = Modifier
                                                    .fillMaxWidth()
                                                    .padding(vertical = 4.dp),
                                                colors = CardDefaults.cardColors(
                                                    containerColor = MaterialTheme.colorScheme.surface
                                                ),
                                                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                                            ) {
                                                Column {
                                                    // 地区标题栏（可点击展开收起）
                                                    Card(
                                                        modifier = Modifier
                                                            .fillMaxWidth()
                                                            .clickable {
                                                                expandedStates[areaName] = !(expandedStates[areaName] ?: true)
                                                            },
                                                        colors = CardDefaults.cardColors(
                                                            containerColor = MaterialTheme.colorScheme.primaryContainer
                                                        ),
                                                        shape = RoundedCornerShape(
                                                            topStart = 12.dp,
                                                            topEnd = 12.dp,
                                                            bottomStart = if (expandedStates[areaName] == true) 0.dp else 12.dp,
                                                            bottomEnd = if (expandedStates[areaName] == true) 0.dp else 12.dp
                                                        )
                                                    ) {
                                                        Row(
                                                            modifier = Modifier
                                                                .fillMaxWidth()
                                                                .padding(12.dp),
                                                            horizontalArrangement = Arrangement.SpaceBetween,
                                                            verticalAlignment = Alignment.CenterVertically
                                                        ) {
                                                                                                                    // 计算该地区所有厨师的采集点总和或技法值总和
                                                        val isLabArea = areaName in listOf("蒸", "炸", "炒", "煮", "切", "烤", "蒸技法", "炸技法", "炒技法", "煮技法", "切技法", "烤技法")
                                                        val totalCollectionPoints = if (isLabArea) {
                                                            // 实验室地区：从计算器获取最终总技法值（包含光环加成）
                                                            CollectionTeamCalculator.getLabAreaTotalSkill(areaName)
                                                        } else {
                                                            // 其他地区：计算采集点总和
                                                            chefs.sumOf { chef ->
                                                                val details = chef.collectionDetails
                                                                when {
                                                                    areaName == "池塘" -> {
                                                                        // 解析"鱼:XX"
                                                                        Regex("鱼:(\\d+)").find(details)?.groupValues?.get(1)?.toIntOrNull() ?: 0
                                                                    }
                                                                    areaName in listOf("牧场", "猪圈", "鸡舍") -> {
                                                                        // 解析"肉:XX"
                                                                        Regex("肉:(\\d+)").find(details)?.groupValues?.get(1)?.toIntOrNull() ?: 0
                                                                    }
                                                                    areaName in listOf("菜棚", "菜地", "森林") -> {
                                                                        // 解析"菜:XX"
                                                                        Regex("菜:(\\d+)").find(details)?.groupValues?.get(1)?.toIntOrNull() ?: 0
                                                                    }
                                                                    areaName == "作坊" -> {
                                                                        // 解析"面:XX"
                                                                        Regex("面:(\\d+)").find(details)?.groupValues?.get(1)?.toIntOrNull() ?: 0
                                                                    }
                                                                    // 玉片区双类型采集点解析
                                                                    areaName in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫") -> {
                                                                        // 解析"肉+菜:XX", "肉+面:XX" 等格式
                                                                        Regex(".*?:(\\d+)").find(details)?.groupValues?.get(1)?.toIntOrNull() ?: 0
                                                                    }
                                                                    else -> 0
                                                                }
                                                            }
                                                        }
                                                        
                                                        // 获取该地区的配置目标值
                                                        val isJadeArea = areaName in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
                                                        // isLabArea 已在上面定义
                                                        val targetCapacity = when {
                                                            isJadeArea -> {
                                                                // 玉片区配置
                                                                val jadeConfigs = getUnifiedAreaConfigs(settings, "jade") as List<JadeAreaItem>
                                                                jadeConfigs.find { it.name == areaName }?.currentCapacity ?: 0
                                                            }
                                                            isLabArea -> {
                                                                // 实验室配置
                                                                val labConfigs = getUnifiedAreaConfigs(settings, "lab") as List<LabItem>
                                                                labConfigs.find { it.name == areaName }?.currentCapacity ?: 0
                                                            }
                                                            else -> {
                                                                // 菜地区配置
                                                                val vegConfigs = getUnifiedAreaConfigs(settings, "veg") as List<VegAreaItem>
                                                                vegConfigs.find { it.name == areaName }?.currentCapacity ?: 0
                                                            }
                                                        }
                                                        
                                                        // 判断是否达到目标
                                                        val isTargetReached = totalCollectionPoints >= targetCapacity
                                                        val capacityColor = if (isTargetReached) Color(0xFF4CAF50) else Color(0xFFF44336)
                                                            
                                                        Row(
                                                            verticalAlignment = Alignment.CenterVertically
                                                        ) {
                                                            Text(
                                                                text = areaName,
                                                                fontSize = 14.sp,
                                                                fontWeight = FontWeight.Bold,
                                                                color = when (areaName) {
                                                                    // 玉片区颜色
                                                                    "朝阴山" -> Color.Black
                                                                    "永昼宫" -> Color.Red
                                                                    "还寒洞" -> Color.Blue
                                                                    "北冥城" -> Color(0xFFFFA500) // 橙色/黄色
                                                                    "藏心亭" -> Color(0xFFFF69B4) // 粉色
                                                                    "清空谷" -> Color(0xFF00AA00) // 绿色
                                                                    // 菜地区颜色
                                                                    "池塘" -> Color.Blue
                                                                    "牧场", "猪圈", "鸡舍" -> Color.Red
                                                                    "菜棚", "菜地", "森林" -> Color(0xFF00AA00) // 绿色
                                                                    "作坊" -> Color(0xFFFFA500) // 黄色
                                                                    else -> MaterialTheme.colorScheme.onPrimaryContainer
                                                                }
                                                            )
                                                            Spacer(modifier = Modifier.width(4.dp))
                                                            Text(
                                                                text = "${chefs.size}人",
                                                                fontSize = 11.sp,
                                                                color = MaterialTheme.colorScheme.onPrimaryContainer,
                                                                modifier = Modifier.alignByBaseline()
                                                            )
                                                            Text(
                                                                text = "｜",
                                                                fontSize = 11.sp,
                                                                color = MaterialTheme.colorScheme.onPrimaryContainer,
                                                                modifier = Modifier.alignByBaseline()
                                                            )
                                                            Text(
                                                                text = if (isLabArea) "总技法值" else "采集点",
                                                                fontSize = 11.sp,
                                                                color = MaterialTheme.colorScheme.onPrimaryContainer,
                                                                modifier = Modifier.alignByBaseline()
                                                            )
                                                            Text(
                                                                text = totalCollectionPoints.toString(),
                                                                fontSize = 11.sp,
                                                                color = capacityColor,
                                                                fontWeight = FontWeight.Bold,
                                                                modifier = Modifier.alignByBaseline()
                                                            )
                                                            // 实验室不显示配置括号，其他地区显示
                                                            if (!isLabArea) {
                                                                Text(
                                                                    text = "($targetCapacity)",
                                                                    fontSize = 11.sp,
                                                                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                                                                    modifier = Modifier.alignByBaseline()
                                                                )
                                                            }
                                                        }
                                                            
                                                            // 保存当前组合按钮（玻璃拟态风格）
                                                            Box(
                                                                modifier = Modifier
                                                                    .height(28.dp)
                                                                    .width(70.dp)
                                                                    .background(
                                                                        color = Color.White.copy(alpha = 0.25f),
                                                                        shape = RoundedCornerShape(14.dp)
                                                                    )
                                                                    .border(
                                                                        width = 1.dp,
                                                                        color = Color.White.copy(alpha = 0.4f),
                                                                        shape = RoundedCornerShape(14.dp)
                                                                    )
                                                                    .clickable {
                                                                        // 创建当前组合的快照
                                                                        val savedChefs = chefs.map { chef ->
                                                                            if (chef is ChefResultWithSkills) {
                                                                                // 获取厨师详细数据用于来源和红色心法盘信息
                                                                                val chefData = gameData?.chefs?.find { it.name == chef.chefName }
                                                                                
                                                                                SavedChefInfo(
                                                                                    name = chef.chefName,
                                                                                    rarity = chef.chefRarity,
                                                                                    area = if (isLabArea) {
                                                                                        // 实验室厨师保存具体的技法类型
                                                                                        when (areaName) {
                                                                                            "蒸技法" -> "蒸"
                                                                                            "炸技法" -> "炸" 
                                                                                            "炒技法" -> "炒"
                                                                                            "煮技法" -> "煮"
                                                                                            "切技法" -> "切"
                                                                                            "烤技法" -> "烤"
                                                                                            else -> areaName
                                                                                        }
                                                                                    } else chef.chefArea,
                                                                                    collectionDetails = chef.chefCollectionDetails,
                                                                                    isUltimate = chef.chefIsUltimate,
                                                                                    // 实验室区域不保存暴击和素材相关字段
                                                                                    critChance = if (isLabArea) 0 else chef.critChance,
                                                                                    critMaterial = if (isLabArea) 0 else chef.critMaterial,
                                                                                    materialGain = if (isLabArea) 0 else chef.materialGain,
                                                                                    baseMeat = if (isLabArea) 0 else chef.baseMeat,
                                                                                    baseFish = if (isLabArea) 0 else chef.baseFish,
                                                                                    baseVeg = if (isLabArea) 0 else chef.baseVeg,
                                                                                    baseCreation = if (isLabArea) 0 else chef.baseCreation,
                                                                                    totalMeat = if (isLabArea) 0 else chef.totalMeat,
                                                                                    totalFish = if (isLabArea) 0 else chef.totalFish,
                                                                                    totalVeg = if (isLabArea) 0 else chef.totalVeg,
                                                                                    totalCreation = if (isLabArea) 0 else chef.totalCreation,
                                                                                    // 添加实验室区域需要的字段
                                                                                    origin = if (isLabArea && chefData != null) chefData.origin else "",
                                                                                    redAmberCount = if (isLabArea && chefData != null) extractRedAmberCount(chefData.diskDesc) else 0

                                                                                )
                                                                            } else {
                                                                                // 获取厨师详细数据用于来源和红色心法盘信息
                                                                                val chefData = gameData?.chefs?.find { it.name == chef.name }
                                                                                
                                                                                SavedChefInfo(
                                                                                    name = chef.name,
                                                                                    rarity = chef.rarity,
                                                                                    area = if (isLabArea) {
                                                                                        // 实验室厨师保存具体的技法类型
                                                                                        when (areaName) {
                                                                                            "蒸技法" -> "蒸"
                                                                                            "炸技法" -> "炸"
                                                                                            "炒技法" -> "炒"
                                                                                            "煮技法" -> "煮"
                                                                                            "切技法" -> "切"
                                                                                            "烤技法" -> "烤"
                                                                                            else -> areaName
                                                                                        }
                                                                                    } else chef.area,
                                                                                    collectionDetails = chef.collectionDetails,
                                                                                    isUltimate = chef.isUltimate,
                                                                                    // 实验室区域不保存暴击和素材相关字段，其他区域保持原逻辑
                                                                                    critChance = if (isLabArea) 0 else 0,
                                                                                    critMaterial = if (isLabArea) 0 else 0,
                                                                                    materialGain = if (isLabArea) 0 else 0,
                                                                                    baseMeat = if (isLabArea) 0 else 0,
                                                                                    baseFish = if (isLabArea) 0 else 0,
                                                                                    baseVeg = if (isLabArea) 0 else 0,
                                                                                    baseCreation = if (isLabArea) 0 else 0,
                                                                                    totalMeat = if (isLabArea) 0 else 0,
                                                                                    totalFish = if (isLabArea) 0 else 0,
                                                                                    totalVeg = if (isLabArea) 0 else 0,
                                                                                    totalCreation = if (isLabArea) 0 else 0,
                                                                                    // 添加实验室区域需要的字段
                                                                                    origin = if (isLabArea && chefData != null) chefData.origin else "",
                                                                                    redAmberCount = if (isLabArea && chefData != null) extractRedAmberCount(chefData.diskDesc) else 0

                                                                                )
                                                                            }
                                                                        }
                                                                        
                                                                        // 对于实验室，提取纯技法名称用于显示
                                                                        val displayAreaName = if (isLabArea) {
                                                                            when (areaName) {
                                                                                "蒸技法" -> "蒸"
                                                                                "炸技法" -> "炸"
                                                                                "炒技法" -> "炒"
                                                                                "煮技法" -> "煮"
                                                                                "切技法" -> "切"
                                                                                "烤技法" -> "烤"
                                                                                else -> areaName
                                                                            }
                                                                        } else areaName
                                                                        
                                                                        val targetAreaName = if (isLabArea) "实验室" else areaName
                                                                        val targetId = if (isLabArea) "实验室_$displayAreaName" else areaName
                                                                        println("DEBUG: 保存组合 - areaName=$areaName, isLabArea=$isLabArea, displayAreaName=$displayAreaName, targetAreaName=$targetAreaName, targetId=$targetId")
                                                                        
                                                                        val combination = SavedCombination(
                                                                            id = targetId, // 实验室使用技法类型区分ID
                                                                            areaName = if (isLabArea) displayAreaName else areaName, // 实验室显示技法名称，其他显示原地区名
                                                                            savedTime = System.currentTimeMillis(),
                                                                            chefs = savedChefs,
                                                                            userId = "" // 用户ID将在saveCombination方法中自动设置
                                                                        )
                                                                        
                                                                        combinationStorage.saveCombination(combination)
                                                                        showSaveSuccessDialog = true
                                                                        
                                                                        // 保存成功后，从查询结果中移除该地区的厨师
                                                                        queryResults = queryResults.filter { result ->
                                                                            result.area != areaName
                                                                        }
                                                                    },
                                                                contentAlignment = Alignment.Center
                                                            ) {
                                                                Text(
                                                                    text = "保存组合",
                                                                    fontSize = 10.sp,
                                                                    fontWeight = FontWeight.Medium,
                                                                    color = Color(0xFF2C3E50).copy(alpha = 0.85f)
                                                                )
                                                            }
                                                            
                                                            Icon(
                                                                imageVector = if (expandedStates[areaName] == true) {
                                                                    Icons.Default.KeyboardArrowUp
                                                                } else {
                                                                    Icons.Default.KeyboardArrowDown
                                                                },
                                                                contentDescription = if (expandedStates[areaName] == true) "收起" else "展开",
                                                                tint = MaterialTheme.colorScheme.onPrimaryContainer
                                                            )
                                                        }
                                                    }
                                                    
                                                    // 厨师列表内容（根据展开状态显示）
                                                    if (expandedStates[areaName] == true) {
                                                        Column {
                                                            // 对于实验室地区，按技法值降序排序，下位上场厨师类型的光环厨师排在第一位
                                                            val sortedChefs = if (areaName in listOf("蒸", "炸", "炒", "煮", "切", "烤")) {
                                                                chefs.sortedWith { chef1, chef2 ->
                                                                    // 检查是否是下位上场厨师类型的光环厨师
                                                                    val isNextPosition1 = gameData?.let { data ->
                                                                        val chefData = data.chefs.find { it.name == chef1.name }
                                                                        chefData?.let { chef ->
                                                                            val skillDescs = chef.getAllUltimateSkills().mapNotNull { skillId ->
                                                                                data.skills.find { it.skillId == skillId }?.desc
                                                                            }
                                                                            skillDescs.any { it.contains("下位上场厨师") }
                                                                        } ?: false
                                                                    } ?: false
                                                                    
                                                                    val isNextPosition2 = gameData?.let { data ->
                                                                        val chefData = data.chefs.find { it.name == chef2.name }
                                                                        chefData?.let { chef ->
                                                                            val skillDescs = chef.getAllUltimateSkills().mapNotNull { skillId ->
                                                                                data.skills.find { it.skillId == skillId }?.desc
                                                                            }
                                                                            skillDescs.any { it.contains("下位上场厨师") }
                                                                        } ?: false
                                                                    } ?: false
                                                                    
                                                                    when {
                                                                        isNextPosition1 && !isNextPosition2 -> -1 // chef1是下位上场厨师，排在前面
                                                                        !isNextPosition1 && isNextPosition2 -> 1  // chef2是下位上场厨师，排在前面
                                                                        else -> {
                                                                            // 都是或都不是下位上场厨师，按技法值降序排序
                                                                            val skillValue1 = chef1.collectionDetails.let { details ->
                                                                                val regex = Regex("技法值: (\\d+)")
                                                                                regex.find(details)?.groupValues?.get(1)?.toIntOrNull() ?: 0
                                                                            }
                                                                            val skillValue2 = chef2.collectionDetails.let { details ->
                                                                                val regex = Regex("技法值: (\\d+)")
                                                                                regex.find(details)?.groupValues?.get(1)?.toIntOrNull() ?: 0
                                                                            }
                                                                            skillValue2.compareTo(skillValue1) // 降序
                                                                        }
                                                                    }
                                                                }
                                                            } else {
                                                                chefs
                                                            }
                                                            
                                                            sortedChefs.forEachIndexed { index, chef ->
                                                                ChefResultRow(
                                                                    item = chef, 
                                                                    gameData = gameData, 
                                                                    personalData = personalData,
                                                                    combinationStorage = combinationStorage,
                                                                    onReplaceChef = { areaName, chefName ->
                                                                        replaceAreaName = areaName
                                                                        replaceChefName = chefName
                                                                        showReplaceDialog = true
                                                                    }
                                                                )
                                                if (index < sortedChefs.lastIndex || sortedChefs.size < 5) {
                                                    HorizontalDivider()
                                                }
                                            }
                                            
                                            // 如果厨师数量不足5人，添加选择厨师卡片
                                            if (sortedChefs.size < 5) {
                                                repeat(5 - sortedChefs.size) { cardIndex ->
                                                    SelectChefCard(
                                                        areaName = areaName,
                                                        onSelectChef = {
                                                            replaceAreaName = areaName
                                                            replaceChefName = "" // 空字符串表示添加新厨师
                                                            showReplaceDialog = true
                                                        }
                                                    )
                                                    if (cardIndex < (5 - chefs.size) - 1) {
                                                        HorizontalDivider()
                                                    }
                                                }
                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                // 其他查询类型按原方式显示
                                LazyColumn {
                                    items(filteredByTab) { item ->
                                        ChefResultRow(
                                            item = item, 
                                            gameData = gameData, 
                                            personalData = personalData,
                                            onReplaceChef = { areaName, chefName ->
                                                replaceAreaName = areaName
                                                replaceChefName = chefName
                                                showReplaceDialog = true
                                            }
                                        )
                                        HorizontalDivider()
                                    }
                                }
                            }
                        }
                    }
                }
            }


        }
    }
}

// VegAreaConfigDialog已删除，使用混合排序功能替代

@Composable
private fun VegAreaConfigDialog(onDismiss: () -> Unit, onShowToast: (String) -> Unit) {
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }
    val combinationStorage = remember { CombinationStorage(context) }
    // 通过调用方提供的回调展示Toast

    // 监听用户切换，当用户切换时刷新已保存配置
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId()) }
    
    // 获取已保存配置的区域名单
    val savedAreaNames = remember(currentUserId) {
        combinationStorage.getAllCombinations().map { it.areaName }.toSet()
    }
    


    // 默认数据（包含描述和采集点数量）
    val allDefaultItems = listOf(
        VegAreaItem("菜棚", "菜", 25, 25, 5, 5),
        VegAreaItem("菜地", "菜", 30, 30, 5, 5),
        VegAreaItem("森林", "菜", 32, 32, 5, 5),
        VegAreaItem("牧场", "肉", 25, 25, 5, 5),
        VegAreaItem("猪圈", "肉", 18, 18, 5, 5),
        VegAreaItem("鸡舍", "肉", 24, 24, 5, 5),
        VegAreaItem("作坊", "面", 26, 26, 5, 5),
        VegAreaItem("池塘", "鱼", 29, 29, 5, 5)
    )
    
    // 过滤掉已保存配置的区域
    val defaultItems = allDefaultItems.filter { item ->
        item.name !in savedAreaNames
    }

    // 如果没有可配置的区域，显示提示
    if (defaultItems.isEmpty()) {
        AlertDialog(
            onDismissRequest = onDismiss,
            title = { Text("菜地区配置") },
            text = { Text("所有菜地区域都已保存配置，无需重复配置。") },
            confirmButton = {
                TextButton(onClick = onDismiss) {
                    Text("确定")
                }
            }
        )
        return
    }

    // 加载已保存顺序，按顺序重新排列
    val savedOrder = settings.getVegAreaOrder()
    var items by remember(currentUserId) {
        mutableStateOf(
            if (savedOrder.isEmpty()) {
                defaultItems.map { item ->
                    val savedPeople = settings.getVegAreaPeople(item.name)
                    val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
                    item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
                }
            } else {
                // 按保存的顺序重新排列，保留原有数据并加载保存的配置
                savedOrder.mapNotNull { savedName ->
                    defaultItems.find { it.name == savedName }?.let { item ->
                        val savedPeople = settings.getVegAreaPeople(item.name)
                        val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
                        item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
                    }
                } + defaultItems.filter { item ->
                    item.name !in savedOrder
                }.map { item ->
                    val savedPeople = settings.getVegAreaPeople(item.name)
                    val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
                    item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
                }
            }
        )
    }
    
    // 监听用户ID变化，当用户切换时刷新菜地区配置
    LaunchedEffect(Unit) {
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId()
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 用户切换了，重新加载菜地区配置
                val newSavedOrder = settings.getVegAreaOrder()
                items = if (newSavedOrder.isEmpty()) {
                    defaultItems.map { item ->
                        val savedPeople = settings.getVegAreaPeople(item.name)
                        val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
                        item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
                    }
                } else {
                    newSavedOrder.mapNotNull { savedName ->
                        defaultItems.find { it.name == savedName }?.let { item ->
                            val savedPeople = settings.getVegAreaPeople(item.name)
                            val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
                            item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
                        }
                    } + defaultItems.filter { item ->
                        item.name !in newSavedOrder
                    }.map { item ->
                        val savedPeople = settings.getVegAreaPeople(item.name)
                        val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
                        item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
                    }
                }
            }
            delay(500) // 每500毫秒检查一次
        }
    }


    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("拖动调整查询优先级（顺序权重）", fontSize = 16.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis) },
        text = {
            val state = rememberReorderableLazyListState(onMove = { from, to ->
                items = items.toMutableList().also { list ->
                    val moved = list.removeAt(from.index)
                    list.add(to.index, moved)
                }
                // 位置变动后自动保存名称顺序
                settings.saveVegAreaOrder(items.map { it.name })
            })
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 500.dp),
                colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
            ) {
                LazyColumn(
                    state = state.listState,
                    modifier = Modifier.reorderable(state)
                ) {
                    itemsIndexed(items, key = { _, it -> it.name }) { index, item ->
                        ReorderableItem(state, key = item.name) { isDragging ->
                            Surface(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 8.dp, vertical = 2.dp),
                                color = Color(0xFFE3F2FD),
                                shape = RoundedCornerShape(8.dp),
                                shadowElevation = if (isDragging) 6.dp else 0.dp
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 12.dp, vertical = 6.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    // 完整的一行布局
                                    Row(
                                        modifier = Modifier.weight(1f),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        // 名称
                                        Text(
                                            text = item.name,
                                            fontSize = 12.sp,
                                            color = when (item.name) {
                                                "池塘" -> Color.Blue
                                                "牧场", "猪圈", "鸡舍" -> Color.Red
                                                "菜棚", "菜地", "森林" -> Color(0xFF00AA00) // 绿色
                                                "作坊" -> Color(0xFFFFA500) // 黄色
                                                else -> MaterialTheme.colorScheme.onPrimaryContainer
                                            },
                                            fontWeight = FontWeight.Medium
                                        )

                                        // 分隔符 ｜
                                        Text(
                                            text = "｜",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // "人数" 文字
                                        Text(
                                            text = "人数",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // 人数下拉框（选项：5, 4, 3, 2, 1, 0，0表示跳过该区域）
                                        SmallDropdownField(
                                            value = item.currentPeople,
                                            onValueChange = { newValue ->
                                                items = items.toMutableList().also { list ->
                                                    list[index] = item.copy(currentPeople = newValue)
                                                }
                                                // 自动保存人数配置
                                                settings.saveVegAreaPeople(item.name, newValue)
                                            },
                                            options = listOf(5, 4, 3, 2, 1, 0),
                                            widthDp = 30.dp
                                        )

                                        // "采集点" 文字
                                        Text(
                                            text = "采集点",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // 采集点下拉框（根据地区显示不同选项）
                                        CollectionDropdownField(
                                            value = item.currentCapacity,
                                            onValueChange = { newValue ->
                                                items = items.toMutableList().also { list ->
                                                    list[index] = item.copy(currentCapacity = newValue)
                                                }
                                                // 自动保存采集点配置
                                                settings.saveVegAreaCapacity(item.name, newValue)
                                            },
                                            areaName = item.name
                                        )
                                    }

                                    // 右侧拖拽图标
                                    Icon(
                                        imageVector = Icons.Default.Menu,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.primary,
                                        modifier = Modifier.detectReorder(state)
                                    )
                                }
                            }
                        }
                        if (index < items.lastIndex) {
                            HorizontalDivider()
                        }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = {
            TextButton(onClick = onDismiss) { Text("关闭") }
        }
    )
}

@Composable
private fun JadeAreaConfigDialog(onDismiss: () -> Unit) {
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }

    data class JadeItem(
        val name: String, 
        val type1: String, 
        val type2: String,
        val currentPeople: Int, 
        val currentCapacity: Int
    )

    // 监听用户切换，当用户切换时刷新配置
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId()) }
    
    // 玉片区地区配置（包含双类型采集点要求）
    val defaultItems = listOf(
        JadeItem("藏心亭", "肉", "菜", 5, 60),
        JadeItem("朝阴山", "肉", "面", 5, 60),
        JadeItem("北冥城", "鱼", "面", 5, 60),
        JadeItem("清空谷", "肉", "鱼", 5, 60),
        JadeItem("还寒洞", "菜", "面", 5, 60),
        JadeItem("永昼宫", "菜", "鱼", 5, 60)
    )
    
    var items by remember(currentUserId) {
        mutableStateOf(
            run {
                val savedOrder = settings.getJadeAreaOrder()
                val ordered = if (savedOrder.isEmpty()) defaultItems.map { it.name } else savedOrder.filter { it in defaultItems.map { item -> item.name } } + defaultItems.map { it.name }.filter { it !in savedOrder }
                ordered.map { name ->
                    val item = defaultItems.find { it.name == name } ?: defaultItems.first()
                    val people = settings.getJadeAreaPeople(name)
                    val capacity = settings.getJadeAreaCapacity(name, 60).coerceAtMost(300)
                    JadeItem(name = name, type1 = item.type1, type2 = item.type2, currentPeople = people, currentCapacity = capacity)
                }
            }
        )
    }
    
    // 监听用户ID变化
    LaunchedEffect(Unit) {
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId()
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 用户切换了，重新加载配置
                val savedOrder = settings.getJadeAreaOrder()
                val ordered = if (savedOrder.isEmpty()) defaultItems.map { it.name } else savedOrder.filter { it in defaultItems.map { item -> item.name } } + defaultItems.map { it.name }.filter { it !in savedOrder }
                items = ordered.map { name ->
                    val item = defaultItems.find { it.name == name } ?: defaultItems.first()
                    val people = settings.getJadeAreaPeople(name)
                    val capacity = settings.getJadeAreaCapacity(name, 60).coerceAtMost(300)
                    JadeItem(name = name, type1 = item.type1, type2 = item.type2, currentPeople = people, currentCapacity = capacity)
                }
            }
            delay(500) // 每500毫秒检查一次
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("拖动调整查询优先级（顺序权重）", fontSize = 16.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis) },
        text = {
            val state = rememberReorderableLazyListState(onMove = { from, to ->
                items = items.toMutableList().also { list ->
                    val moved = list.removeAt(from.index)
                    list.add(to.index, moved)
                }
                settings.saveJadeAreaOrder(items.map { it.name })
            })
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 500.dp),
                colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
            ) {
                LazyColumn(
                    state = state.listState,
                    modifier = Modifier.reorderable(state)
                ) {
                    itemsIndexed(items, key = { _, it -> it.name }) { index, item ->
                        ReorderableItem(state, key = item.name) { isDragging ->
                            Surface(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 8.dp, vertical = 2.dp),
                                color = Color(0xFFE3F2FD),
                                shape = RoundedCornerShape(8.dp),
                                shadowElevation = if (isDragging) 6.dp else 0.dp
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 12.dp, vertical = 6.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Row(
                                        modifier = Modifier.weight(1f),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        Text(
                                            text = item.name,
                                            fontSize = 12.sp,
                                            color = when (item.name) {
                                                "朝阴山" -> Color.Black
                                                "永昼宫" -> Color.Red
                                                "还寒洞" -> Color.Blue
                                                "北冥城" -> Color(0xFFFFA500) // 橙色/黄色
                                                "藏心亭" -> Color(0xFFFF69B4) // 粉色
                                                "清空谷" -> Color(0xFF00AA00) // 绿色
                                                else -> MaterialTheme.colorScheme.onPrimaryContainer
                                            },
                                            fontWeight = FontWeight.Medium
                                        )

                                        Text(
                                            text = "｜",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )



                                        Text(
                                            text = "人数",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // 人数下拉框（选项：5, 4, 3, 2, 1, 0，0表示跳过该区域）
                                        SmallDropdownField(
                                            value = item.currentPeople,
                                            onValueChange = { newValue ->
                                                items = items.toMutableList().also { list ->
                                                    list[index] = item.copy(currentPeople = newValue)
                                                }
                                                // 自动保存人数配置
                                                settings.saveJadeAreaPeople(item.name, newValue)
                                            },
                                            options = listOf(5, 4, 3, 2, 1, 0),
                                            widthDp = 30.dp
                                        )

                                        Text(
                                            text = "采集点",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // 采集点下拉框（15-165，每增加15点为一档，降序排序，默认60）
                                        SmallDropdownField(
                                            value = item.currentCapacity,
                                            onValueChange = { newValue ->
                                                items = items.toMutableList().also { list ->
                                                    list[index] = item.copy(currentCapacity = newValue)
                                                }
                                                // 自动保存采集点配置
                                                settings.saveJadeAreaCapacity(item.name, newValue)
                                            },
                                            options = (165 downTo 15 step 15).toList(), // 165,150,135,120,105,90,75,60,45,30,15
                                            widthDp = 45.dp
                                        )
                                    }

                                    Icon(
                                        imageVector = Icons.Default.Menu,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.primary,
                                        modifier = Modifier.detectReorder(state)
                                    )
                                }
                            }
                        }
                        if (index < items.lastIndex) {
                            HorizontalDivider()
                        }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = { TextButton(onClick = onDismiss) { Text("关闭") } }
    )
}

@Composable
private fun CondAreaConfigDialog(onDismiss: () -> Unit) {
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }

    // 监听用户切换，当用户切换时刷新配置
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId()) }
    
    val defaultNames = listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁")
    var items by remember(currentUserId) {
        mutableStateOf(
            run {
                val savedOrder = settings.getCondAreaOrder()
                val ordered = if (savedOrder.isEmpty()) defaultNames else savedOrder.filter { it in defaultNames } + defaultNames.filter { it !in savedOrder }
                ordered.map { name ->
                    val people = settings.getCondAreaPeople(name)
                    val capacity = settings.getCondAreaCapacity(name, 60).coerceAtMost(300)
                    CondItem(name = name, currentPeople = people, currentCapacity = capacity)
                }
            }
        )
    }
    
    // 监听用户ID变化
    LaunchedEffect(Unit) {
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId()
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 用户切换了，重新加载配置
                val savedOrder = settings.getCondAreaOrder()
                val ordered = if (savedOrder.isEmpty()) defaultNames else savedOrder.filter { it in defaultNames } + defaultNames.filter { it !in savedOrder }
                items = ordered.map { name ->
                    val people = settings.getCondAreaPeople(name)
                    val capacity = settings.getCondAreaCapacity(name, 60).coerceAtMost(300)
                    CondItem(name = name, currentPeople = people, currentCapacity = capacity)
                }
            }
            delay(500) // 每500毫秒检查一次
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("拖动调整查询优先级（顺序权重）", fontSize = 16.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis) },
        text = {
            val state = rememberReorderableLazyListState(onMove = { from, to ->
                items = items.toMutableList().also { list ->
                    val moved = list.removeAt(from.index)
                    list.add(to.index, moved)
                }
                settings.saveCondAreaOrder(items.map { it.name })
            })
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 500.dp),
                colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
            ) {
                LazyColumn(
                    state = state.listState,
                    modifier = Modifier.reorderable(state)
                ) {
                    itemsIndexed(items, key = { _, it -> it.name }) { index, item ->
                        ReorderableItem(state, key = item.name) { isDragging ->
                            Surface(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 8.dp, vertical = 2.dp),
                                color = Color(0xFFE3F2FD),
                                shape = RoundedCornerShape(8.dp),
                                shadowElevation = if (isDragging) 6.dp else 0.dp
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 12.dp, vertical = 6.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Row(
                                        modifier = Modifier.weight(1f),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        Text(
                                            text = item.name,
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer,
                                            fontWeight = FontWeight.Medium
                                        )

                                        Text(
                                            text = "｜",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        Text(
                                            text = "人数",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // 人数下拉框（选项：5, 4, 3, 2, 1, 0，0表示跳过该区域）
                                        SmallDropdownField(
                                            value = item.currentPeople,
                                            onValueChange = { newValue ->
                                                items = items.toMutableList().also { list ->
                                                    list[index] = item.copy(currentPeople = newValue)
                                                }
                                                // 自动保存人数配置
                                                settings.saveCondAreaPeople(item.name, newValue)
                                            },
                                            options = listOf(5, 4, 3, 2, 1, 0),
                                            widthDp = 30.dp
                                        )

                                        Text(
                                            text = "采集点",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // 采集点下拉框（目前只有一档，默认60）
                                        SmallDropdownField(
                                            value = item.currentCapacity,
                                            onValueChange = { newValue ->
                                                items = items.toMutableList().also { list ->
                                                    list[index] = item.copy(currentCapacity = newValue)
                                                }
                                                // 自动保存采集点配置
                                                settings.saveCondAreaCapacity(item.name, newValue)
                                            },
                                            options = listOf(60), // 目前只有一档
                                            widthDp = 45.dp
                                        )
                                    }

                                    Icon(
                                        imageVector = Icons.Default.Menu,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.primary,
                                        modifier = Modifier.detectReorder(state)
                                    )
                                }
                            }
                        }
                        if (index < items.lastIndex) {
                            HorizontalDivider()
                        }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = { TextButton(onClick = onDismiss) { Text("关闭") } }
    )
}

// 采集点详情悬浮窗
@Composable
private fun CollectionDetailsDialog(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?,
    onDismiss: () -> Unit
) {
    // 采集点详情 - 长按显示理论最大值，松开回到当前加成
    var showTheoreticalMax by remember { mutableStateOf(false) }
    
    // 判断是否为菜地区，决定是否使用银布鞋逻辑
    val isVegArea = chef.chefArea in listOf("池塘", "牧场", "猪圈", "鸡舍", "菜棚", "菜地", "森林", "作坊")
    // 判断是否为玉片区，决定是否使用玉片区银布鞋逻辑
    val isJadeArea = chef.chefArea in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }
    
    // 根据地区类型选择对应的银布鞋开关
    val actualUseSilverShoes = when {
        isVegArea -> settings.getUseSilverShoes()
        isJadeArea -> settings.getUseJadeSilverShoes()
        else -> false
    }
    
    // 根据地区类型选择对应的满级心法盘开关
    val actualUseMaxLevelAmber = when {
        isVegArea -> settings.getUseMaxLevelAmber()
        isJadeArea -> settings.getUseJadeMaxLevelAmber()
        else -> false
    }
    
    Dialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(
            dismissOnBackPress = true,
            dismissOnClickOutside = true
        )
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ) {
                    // 点击切换显示模式
                    showTheoreticalMax = !showTheoreticalMax
                },
            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
            shape = RoundedCornerShape(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                // 标题
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = "${chef.name} 采集点详情",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                                         // 显示绿色心法盘数量
                     if (gameData != null) {
                         val chefData = gameData.chefs.find { it.name == chef.name }
                         if (chefData != null) {
                             val greenAmberCount = extractGreenAmberCount(chefData.diskDesc)
                             val displayText = if (greenAmberCount > 0) {
                                 "绿色心法盘X$greenAmberCount"
                             } else {
                                 "无绿色心法盘"
                             }
                             Text(
                                 text = displayText,
                                 fontSize = 12.sp,
                                 fontWeight = FontWeight.Normal,
                                 color = Color(0xFF4CAF50) // 绿色
                             )
                         }
                     }
                }
                
                HorizontalDivider()
                
                // 缓存理论最大值计算结果，避免每次切换都重新计算
                val theoreticalMaxValues = remember(chef, gameData, personalData, actualUseSilverShoes) {
                    calculateTheoreticalMaxValues(chef, gameData, personalData, actualUseSilverShoes)
                }
                
                // 缓存当前装备信息
                val currentEquipInfo = remember(chef, gameData, personalData, actualUseSilverShoes, actualUseMaxLevelAmber) {
                    if (isJadeArea && actualUseMaxLevelAmber) {
                        // 玉片区开启满级心法盘时，显示满级心法盘信息
                        getJadeMaxLevelEquipmentInfo(chef, gameData, personalData, actualUseSilverShoes)
                    } else {
                    getCurrentEquipmentInfo(chef, gameData, personalData, actualUseSilverShoes)
                    }
                }
                
                // 显示装备信息 - 使用不同字体大小
                val titleText = if (showTheoreticalMax) "理论最大" else "当前加成"
                val equipName = if (showTheoreticalMax) theoreticalMaxValues.equipName else currentEquipInfo.equipName
                val amberNames = if (showTheoreticalMax) theoreticalMaxValues.amberNames else currentEquipInfo.amberNames
                
                // 计算双采集点的理论最大值（仅玉片区显示）
                val dualCollectionInfo = if (showTheoreticalMax && isJadeArea(chef.chefArea)) {
                    calculateDualCollectionTheoreticalMax(chef, theoreticalMaxValues)
                } else null
                
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    // 标题部分保持原字体大小
                    Text(
                        text = titleText,
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                    // 装备信息部分使用小字体
                    if (equipName.isNotEmpty() || amberNames.isNotEmpty() || dualCollectionInfo != null) {
                        Text(
                            text = " ",
                            fontSize = 12.sp,
                            color = MaterialTheme.colorScheme.primary
                        )
                        
                        val equipParts = mutableListOf<String>()
                        if (dualCollectionInfo != null) {
                            equipParts.add(dualCollectionInfo)
                        }
                        if (equipName.isNotEmpty()) {
                            equipParts.add("厨具：$equipName")
                        }
                        if (amberNames.isNotEmpty()) {
                            equipParts.add("心法盘：${amberNames.joinToString("、")}")
                        }
                        
                        Text(
                            text = equipParts.joinToString("｜"),
                            fontSize = 9.sp,
                            fontWeight = FontWeight.Normal,
                            color = MaterialTheme.colorScheme.primary,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                            modifier = Modifier.weight(1f)
                        )
                    }
                }
                
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        Column(modifier = Modifier.weight(1f)) {
                            CollectionDetailRow(
                                type = "肉",
                                baseValue = chef.baseMeat,
                                totalValue = if (showTheoreticalMax) theoreticalMaxValues.meat else chef.totalMeat,
                                color = Color(0xFFE57373)
                            )
                        }
                        Column(modifier = Modifier.weight(1f)) {
                            CollectionDetailRow(
                                type = "鱼",
                                baseValue = chef.baseFish,
                                totalValue = if (showTheoreticalMax) theoreticalMaxValues.fish else chef.totalFish,
                                color = Color(0xFF64B5F6)
                            )
                        }
                    }
                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        Column(modifier = Modifier.weight(1f)) {
                            CollectionDetailRow(
                                type = "菜",
                                baseValue = chef.baseVeg,
                                totalValue = if (showTheoreticalMax) theoreticalMaxValues.veg else chef.totalVeg,
                                color = Color(0xFF81C784)
                            )
                        }
                        Column(modifier = Modifier.weight(1f)) {
                            CollectionDetailRow(
                                type = "面",
                                baseValue = chef.baseCreation,
                                totalValue = if (showTheoreticalMax) theoreticalMaxValues.creation else chef.totalCreation,
                                color = Color(0xFFFFB74D)
                            )
                        }
                    }
                }
                
                HorizontalDivider()
                
                // 说明文字
                Text(
                    text = if (showTheoreticalMax) 
                        "点击查看当前加成" 
                    else 
                        "点击查看理论最大加成",
                    fontSize = 10.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.fillMaxWidth(),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}

// 理论最大值数据类
private data class TheoreticalMaxValues(
    val meat: Int,
    val fish: Int,
    val veg: Int,
    val creation: Int,
    val equipName: String = "",
    val amberNames: List<String> = emptyList()
)

// 当前加成装备信息数据类
private data class CurrentEquipmentInfo(
    val equipName: String = "",
    val amberNames: List<String> = emptyList()
)

// 计算理论最大值
private fun calculateTheoreticalMaxValues(
    chef: ChefResultWithSkills, 
    gameData: GameData?, 
    personalData: PersonalData?
): TheoreticalMaxValues {
    return calculateTheoreticalMaxValues(chef, gameData, personalData, false)
}

private fun calculateTheoreticalMaxValues(
    chef: ChefResultWithSkills, 
    gameData: GameData?, 
    personalData: PersonalData?,
    useSilverShoes: Boolean = false
): TheoreticalMaxValues {
    if (gameData == null) {
        // 游戏数据未加载，返回当前值
        return TheoreticalMaxValues(
            meat = chef.totalMeat,
            fish = chef.totalFish,
            veg = chef.totalVeg,
            creation = chef.totalCreation
        )
    }
    
    // 1. 根据厨师当前分配的地区确定心法盘/厨具加成类型
    // 对于玉片区，固定选择双类型中的第一个；对于其他地区，使用原来的逻辑
    val currentAreaType = determineFirstAreaType(chef.chefArea)
    
    
    // 2. 确定最佳厨具加成（根据当前分配类型判断当前佩戴厨具是否满足，否则用65）
    val bestEquipBonusForType = calculateBestEquipBonus(chef, gameData, personalData, currentAreaType, useSilverShoes)
    
    // 3. 同步计算"当前加成页同款规则"的四类厨具加成（识别全采集/单类型）
    val usedEquipName = getTheoreticalBestEquipName(chef, gameData, personalData, currentAreaType, useSilverShoes)
    val usedEquip = gameData.equips.find { it.name == usedEquipName }
    val equipBonusAllTypes = usedEquip?.let { calculateEquipBonusAllTypes(it, gameData) } ?: EquipCollectionBonus()
    val hasDoubleSkill = checkHasDoubleSkill(chef, gameData)
    val equipBonusAllTypesFinal = if (hasDoubleSkill) {
        EquipCollectionBonus(
            meat = equipBonusAllTypes.meat * 2,
            fish = equipBonusAllTypes.fish * 2,
            veg = equipBonusAllTypes.veg * 2,
            creation = equipBonusAllTypes.creation * 2
        )
    } else equipBonusAllTypes
    
    // 4. 只为当前地区类型计算心法盘加成
    val maxAmberBonusMeat = if (currentAreaType == "肉") calculateMaxAmberBonusForType(chef, gameData, "肉") else 0
    val maxAmberBonusFish = if (currentAreaType == "鱼") calculateMaxAmberBonusForType(chef, gameData, "鱼") else 0
    val maxAmberBonusVeg = if (currentAreaType == "菜") calculateMaxAmberBonusForType(chef, gameData, "菜") else 0
    val maxAmberBonusCreation = if (currentAreaType == "面") calculateMaxAmberBonusForType(chef, gameData, "面") else 0
    
    // 5. 获取理论最大值使用的装备信息
    val theoreticalEquipInfo = getTheoreticalEquipmentInfo(chef, gameData, personalData, currentAreaType, useSilverShoes)
    
    return TheoreticalMaxValues(
        meat = chef.baseMeat + equipBonusAllTypesFinal.meat + maxAmberBonusMeat,
        fish = chef.baseFish + equipBonusAllTypesFinal.fish + maxAmberBonusFish,
        veg = chef.baseVeg + equipBonusAllTypesFinal.veg + maxAmberBonusVeg,
        creation = chef.baseCreation + equipBonusAllTypesFinal.creation + maxAmberBonusCreation,
        equipName = theoreticalEquipInfo.equipName,
        amberNames = theoreticalEquipInfo.amberNames
    )
}

// 根据地区名称确定采集类型
private fun determineAreaType(areaName: String): String {
    return when {
        areaName.contains("池塘") -> "鱼"
        areaName.contains("森林") || areaName.contains("菜棚") || areaName.contains("菜地") -> "菜"
        areaName.contains("牧场") || areaName.contains("猪圈") || areaName.contains("鸡舍") -> "肉"
        areaName.contains("作坊") -> "面"
        else -> ""
    }
}

// 根据地区名称确定双类型采集点，并固定选择第一个类型
private fun determineFirstAreaType(areaName: String): String {
    val dualTypes = when (areaName) {
        "藏心亭" -> listOf("肉", "菜")
        "朝阴山" -> listOf("肉", "面")
        "北冥城" -> listOf("鱼", "面")
        "清空谷" -> listOf("肉", "鱼")
        "还寒洞" -> listOf("菜", "面")
        "永昼宫" -> listOf("菜", "鱼")
        else -> emptyList()
    }
    
    return if (dualTypes.isNotEmpty()) {
        // 固定选择第一个类型
        dualTypes.first()
    } else {
        // 如果不是玉片区，使用原来的逻辑
        determineAreaType(areaName)
    }
}

// 计算最佳厨具加成
private fun calculateBestEquipBonus(chef: ChefResultWithSkills, gameData: GameData, personalData: PersonalData?, currentAreaType: String): Int {
    return calculateBestEquipBonus(chef, gameData, personalData, currentAreaType, false)
}

private fun calculateBestEquipBonus(chef: ChefResultWithSkills, gameData: GameData, personalData: PersonalData?, currentAreaType: String, useSilverShoes: Boolean): Int {
    // 首先检查厨师当前佩戴的厨具
    val chefData = gameData.chefs.find { it.name == chef.chefName }
    if (chefData != null && personalData != null) {
        val personalChef = personalData.chefs[chefData.chefId]
        
        if (useSilverShoes) {
            // 银布鞋逻辑
            if (personalChef != null && personalChef.equip != null) {
                val currentEquipId = personalChef.equip.toString()
                // 如果是指定厨具ID则使用，否则用65号厨具
                if (currentEquipId in listOf("1088", "76", "77", "78", "64", "841")) {
                    val equip = gameData.equips.find { it.equipId == currentEquipId }
                    if (equip != null) {
                        val bonus = calculateEquipCollectionBonusByType(equip, gameData, currentAreaType)
                        return bonus
                    }
                }
            }
            // 没有装备或不是指定厨具，使用65号厨具（银布鞋）
        } else {
            // 原有逻辑
            if (personalChef != null && personalChef.equip != null) {
                val currentEquipId = personalChef.equip.toString()
                // 若佩戴为 1088/76/77/78/64/841 之一，直接使用
                if (currentEquipId in listOf("1088", "76", "77", "78", "64", "841")) {
                    val equip = gameData.equips.find { it.equipId == currentEquipId }
                    if (equip != null) {
                        val bonus = calculateEquipCollectionBonusByType(equip, gameData, currentAreaType)
                        return bonus
                    }
                } else {
                    // 否则检查当前佩戴厨具对当前分配类型的加成是否>=2，否则用65
                    val equip = gameData.equips.find { it.equipId == currentEquipId }
                    if (equip != null) {
                        val typeBonus = calculateEquipCollectionBonusByType(equip, gameData, currentAreaType)
                        if (typeBonus >= 2) {
                            return typeBonus
                        }
                    }
                }
            }
        }
    }
    
    // 否则使用65号厨具
    val defaultEquip = gameData.equips.find { it.equipId == "65" }
    if (defaultEquip != null) {
        val bonus = calculateEquipCollectionBonusByType(defaultEquip, gameData, currentAreaType)
        return bonus
    }
    
    return 0 // 没有找到厨具
}

// 计算厨具的采集点加成
private fun calculateEquipCollectionBonus(equip: Equip, gameData: GameData): Int {
    var maxCollectionBonus = 0
    
    equip.skill.forEach { skillId ->
        val skill = gameData.skills.find { it.skillId == skillId }
        skill?.let { skillObj ->
            // 从技能描述中解析采集点加成
            val bonus = parseCollectionBonusFromDesc(skillObj.desc)
            maxCollectionBonus = maxOf(maxCollectionBonus, bonus)
        }
    }
    
    return maxCollectionBonus
}

// 计算特定类型的心法盘最高等级加成
private fun calculateMaxAmberBonusForType(chef: ChefResultWithSkills, gameData: GameData, targetType: String): Int {
    // 根据厨师星级确定心法盘最高等级
    val maxLevel = when (chef.chefRarity) {
        5 -> 5 // 五星厨师，心法盘最高5级
        4 -> 4 // 四星厨师，心法盘最高4级
        else -> 3 // 三星及以下，心法盘最高3级
    }
    
    // 查找厨师数据以获取diskDesc信息
    val chefData = gameData.chefs.find { it.name == chef.chefName }
    if (chefData == null) {
        return 0
    }
    
    // 解析diskDesc获取绿色心法盘数量
    val greenAmberCount = parseGreenAmberCount(chefData.diskDesc)
    if (greenAmberCount == 0) return 0
    
    // 寻找该类型的绿色心法盘的最高加成
    var maxSingleAmberBonus = 0
    
    gameData.ambers.forEach { amber ->
        if (amber.type == 2) { // 绿色心法盘
            amber.skill.forEach { skillId ->
                val skill = gameData.skills.find { it.skillId == skillId }
                skill?.let { skillObj ->
                    val desc = skillObj.desc
                    // 检查技能效果是否匹配目标类型
                    val isMatchingType = when (targetType) {
                        "肉" -> desc.contains("肉类") || desc.contains("Meat") || desc.contains("畜产")
                        "鱼" -> desc.contains("鱼类") || desc.contains("Fish") || desc.contains("水产")
                        "菜" -> desc.contains("菜类") || desc.contains("Veg") || desc.contains("素产") || desc.contains("蔬菜")
                        "面" -> desc.contains("加工") || desc.contains("Creation") || desc.contains("加工类") || desc.contains("面类")
                        else -> false
                    }
                    
                    if (isMatchingType) {
                        // 解析基础加成值
                        val baseBonus = parseCollectionBonusFromDesc(desc)
                        if (baseBonus > 0) {
                                                    // 计算最高等级的总加成
                        val levelBonus = if (maxLevel > 1) amber.amplification * (maxLevel - 1) else 0
                        val totalBonus = baseBonus + levelBonus
                        maxSingleAmberBonus = maxOf(maxSingleAmberBonus, totalBonus)
                        }
                    }
                }
            }
        }
    }
    
    val finalBonus = maxSingleAmberBonus * greenAmberCount
    
    // 返回：单个心法盘最高加成 × 绿色心法盘数量
    return finalBonus
}

// 解析diskDesc获取绿色心法盘数量
private fun parseGreenAmberCount(diskDesc: String): Int {
    if (diskDesc.isEmpty()) return 0
    
    // 解析类似 "蓝|绿|绿<br>最高5级" 的格式
    val diskTypes = diskDesc.split("<br>")[0] // 取第一部分，去掉等级描述
    val types = diskTypes.split("|")
    
    var greenCount = 0
    for (type in types) {
        if (type.trim() == "绿") {
            greenCount++
        }
    }
    
    return greenCount
}

// 从技能描述中解析采集点加成数值
private fun parseCollectionBonusFromDesc(desc: String): Int {
    // 匹配类似 "水产采集+3", "采集获得肉类食材+2个", "采集点+4" 等模式
    val patterns = listOf(
        Regex("采集\\+(\\d+)"),           // 采集+数字
        Regex("采集获得.*?\\+(\\d+)个?"),   // 采集获得...+数字个
        Regex("水产采集\\+(\\d+)"),        // 水产采集+数字
        Regex("畜产采集\\+(\\d+)"),        // 畜产采集+数字
        Regex("素产采集\\+(\\d+)"),        // 素产采集+数字
        Regex("加工采集\\+(\\d+)"),        // 加工采集+数字
        Regex("(\\d+)个.*?食材"),         // 数字个...食材
        Regex("技法\\+(\\d+)")            // 技法+数字
    )
    
    for (pattern in patterns) {
        val match = pattern.find(desc)
        if (match != null) {
            val value = match.groupValues[1].toIntOrNull()
            if (value != null && value > 0) {
                return value
            }
        }
    }
    
    return 0
}

// 检查是否有528技能（厨具效果翻倍）
private fun checkHasDoubleSkill(chef: ChefResultWithSkills, gameData: GameData): Boolean {
    if (!chef.chefIsUltimate) return false
    
    // 查找厨师数据
    val chefData = gameData.chefs.find { it.name == chef.chefName }
    if (chefData == null || !chefData.hasUltimateSkill()) return false
    
    // 检查修炼技能中是否有厨具效果翻倍技能
    for (skillId in chefData.getAllUltimateSkills()) {
        val skill = gameData.skills.find { it.skillId == skillId }
        if (skill?.desc?.contains("厨具技能效果翻倍") == true) {
            return true
        }
    }
    
    return false
}



// 单行采集点详情
@Composable
private fun CollectionDetailRow(
    type: String,
    baseValue: Int,
    totalValue: Int,
    color: Color
) {
    val bonus = totalValue - baseValue
    
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                color = color.copy(alpha = 0.1f),
                shape = RoundedCornerShape(8.dp)
            )
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Start
    ) {
        // 类型标识
        Box(
            modifier = Modifier
                .size(22.dp)
                .background(
                    color = color,
                    shape = RoundedCornerShape(4.dp)
                ),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = type,
                fontSize = 10.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White
            )
        }
        
        Spacer(modifier = Modifier.width(8.dp))
        
        // 采集点数值
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(4.dp),
            modifier = Modifier.weight(1f)
        ) {
            // 基础值
            Text(
                text = baseValue.toString(),
                fontSize = 13.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 1,
                overflow = TextOverflow.Visible
            )
            
            // 加成显示
            if (bonus > 0) {
                Text(
                    text = "+$bonus",
                    fontSize = 11.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF4CAF50),
                    maxLines = 1,
                    overflow = TextOverflow.Visible
                )
                
                Text(
                    text = "= $totalValue",
                    fontSize = 13.sp,
                    fontWeight = FontWeight.Bold,
                    color = color,
                    maxLines = 1,
                    overflow = TextOverflow.Visible
                )
            } else {
                Text(
                    text = "= $totalValue",
                    fontSize = 13.sp,
                    fontWeight = FontWeight.Bold,
                    color = color,
                    maxLines = 1,
                    overflow = TextOverflow.Visible
                )
            }
        }
    }
}

@Composable
private fun ChefResultRow(
    item: ChefResult, 
    gameData: GameData?, 
    personalData: PersonalData?,
    combinationStorage: CombinationStorage? = null,
    onReplaceChef: ((String, String) -> Unit)? = null, // 替换厨师回调，参数：地区名，厨师名
    currentQueryResults: List<ChefResult>? = null, // 当前查询结果，用于显示已分配信息
    isInReplaceDialog: Boolean = false // 是否在替换弹窗中
) {
    // 控制悬浮窗显示状态
    var showCollectionDialog by remember { mutableStateOf(false) }
    var showCritDetailsDialog by remember { mutableStateOf(false) }
    
    // 判断是否为实验室地区（在外层作用域定义）
            val isLabArea = item.area in listOf("蒸", "炸", "炒", "煮", "切", "烤")
    
    Box(modifier = Modifier.padding(8.dp)) {
        Column {
            // 第一行：名称 + 星级 + 绿色心法盘数量 + 替换按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.weight(1f)
                ) {
                    Text(text = item.name, fontSize = 14.sp, fontWeight = FontWeight.Medium)
                    Spacer(modifier = Modifier.width(6.dp))
                    repeat(item.rarity) {
                        Icon(
                            imageVector = Icons.Default.Star,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(12.dp)
                        )
                    }
                    
                    // 显示心法盘数量（实验室显示红色，其他显示绿色）
                    if (gameData != null) {
                        val chefData = gameData.chefs.find { it.name == item.name }
                        if (chefData != null) {
                            if (isLabArea) {
                                // 实验室地区显示红色心法盘数量
                                val redAmberCount = extractRedAmberCount(chefData.diskDesc)
                                val displayText = if (redAmberCount > 0) {
                                    "红色心法盘X$redAmberCount"
                                } else {
                                    "无红色心法盘"
                                }
                                Spacer(modifier = Modifier.width(4.dp))
                                Text(
                                    text = displayText,
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Normal,
                                    color = Color(0xFFF44336) // 红色
                                )
                            } else {
                                // 其他地区显示绿色心法盘数量
                                val greenAmberCount = extractGreenAmberCount(chefData.diskDesc)
                                val displayText = if (greenAmberCount > 0) {
                                    "绿色心法盘X$greenAmberCount"
                                } else {
                                    "无绿色心法盘"
                                }
                                Spacer(modifier = Modifier.width(4.dp))
                                Text(
                                    text = displayText,
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Normal,
                                    color = Color(0xFF4CAF50) // 绿色
                                )
                            }
                        }
                    }
                    
                    // 在替换弹窗中显示已分配信息（移到第一行）
                    if (isInReplaceDialog && currentQueryResults != null) {
                        val assignedArea = currentQueryResults.find { it.name == item.name }?.area
                        if (assignedArea != null) {
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "已分配给：$assignedArea",
                                fontSize = 10.sp,
                                color = Color.Red,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                }
                
                // 替换按钮（玻璃拟态风格）
                if (onReplaceChef != null) {
                    Box(
                        modifier = Modifier
                            .width(40.dp)
                            .height(24.dp)
                            .background(
                                color = Color.White.copy(alpha = 0.25f),
                                shape = RoundedCornerShape(12.dp)
                            )
                            .border(
                                width = 1.dp,
                                color = Color.Black.copy(alpha = 0.3f),
                                shape = RoundedCornerShape(12.dp)
                            )
                            .clickable { onReplaceChef(item.area, item.name) },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "替换",
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Medium,
                            color = Color(0xFF2C3E50).copy(alpha = 0.85f)
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(4.dp))

            // 第二行：采集点详情 + 详情按钮
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 根据地区类型显示高亮的采集点信息
                if (item.collectionDetails.isNotEmpty()) {
                    // 判断是否为菜地区（显示四种采集类型）
                    val isVegArea = item.area in listOf("池塘", "牧场", "猪圈", "鸡舍", "菜棚", "菜地", "森林", "作坊")
                    
                    if (isVegArea) {
                        // 确定该地区对应的采集类型
                        val targetType = when (item.area) {
                            "池塘" -> "鱼"
                            "牧场", "猪圈", "鸡舍" -> "肉"
                            "菜棚", "菜地", "森林" -> "菜"
                            "作坊" -> "面"
                            else -> ""
                        }
                        
                        // 解析采集点详情并高亮显示
                        Row {
                            val collectionParts = item.collectionDetails.split(" ")
                            collectionParts.forEachIndexed { index, part ->
                                if (index > 0) {
                                    Text(
                                        text = " ",
                                        fontSize = 12.sp,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                                
                                // 判断当前部分是否为目标类型
                                val isTargetType = part.startsWith("$targetType:")
                                
                                Text(
                                    text = part,
                                    fontSize = 12.sp,
                                    color = if (isTargetType) Color(0xFFF44336) else MaterialTheme.colorScheme.onSurfaceVariant,
                                    fontWeight = if (isTargetType) FontWeight.Bold else FontWeight.Normal
                                )
                            }
                        }
                    } else {
                        // 玉片区高亮显示
                        val isJadeArea = item.area in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
                        
                        if (isJadeArea) {
                            // 玉片区显示双类型采集点，整个内容标红
                            Text(
                                text = item.collectionDetails,
                                fontSize = 12.sp,
                                color = Color(0xFFF44336), // 红色高亮
                                fontWeight = FontWeight.Bold
                            )
                        } else {
                            if (isLabArea) {
                                // 实验室地区显示技法值和光环（同一行）
                                Text(
                                    text = buildAnnotatedString {
                                        val details = item.collectionDetails
                                        val auraStartIndex = details.indexOf("（光环：")
                                        
                                        if (auraStartIndex != -1) {
                                            // 有光环信息，技法值红色，光环灰色
                                            val skillPart = details.substring(0, auraStartIndex)
                                            val auraPart = details.substring(auraStartIndex)
                                            
                                            withStyle(style = SpanStyle(color = Color(0xFFF44336), fontWeight = FontWeight.Bold)) {
                                                append(skillPart)
                                            }
                                            withStyle(style = SpanStyle(color = Color.Gray)) {
                                                append(auraPart)
                                            }
                                        } else {
                                            // 没有光环信息，技法值红色显示
                                            withStyle(style = SpanStyle(color = Color(0xFFF44336), fontWeight = FontWeight.Bold)) {
                                                append(details)
                                            }
                                        }
                                    },
                                    fontSize = 12.sp
                                )
                            } else {
                                // 其他地区正常显示
                                Text(
                                    text = item.collectionDetails,
                                    fontSize = 12.sp,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                } else {
                    Text(
                        text = "采集点: ${item.area}",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                // 非实验室区域显示感叹号图标和采集期望值
                if (!isLabArea) {
                    if (item is ChefResultWithSkills) {
                        Spacer(modifier = Modifier.width(4.dp))
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = "查看详情",
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier
                                .size(14.dp)
                                .clickable { showCollectionDialog = true }
                        )
                    }
                    
                    // 显示期望值（智能技能评分）- 替换原来的厨师来源位置
                    if (item is ChefResultWithSkills) {
                        // 计算期望值：素材加成 + (暴击率 × 暴击素材)
                        val expectationValue = item.materialGain + (item.critChance / 100.0 * item.critMaterial)
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "采集期望值：${String.format("%.0f", expectationValue)}",
                            fontSize = 10.sp,
                            color = Color(0xFF9C27B0), // 紫色
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
                

            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 第三行：厨师来源和拥有/修炼状态（仅实验室地区显示）
            if (isLabArea && gameData != null) {
                val chefData = gameData.chefs.find { it.name == item.name }
                if (chefData != null) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "来源：${chefData.origin.replace("<br>", "、")}",
                            fontSize = 11.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            fontWeight = FontWeight.Normal,
                            modifier = Modifier.weight(1f)
                        )
                        
                        // 拥有/修炼状态显示
                        if (!item.owned) {
                            // 未拥有只显示拥有状态
                            Text(
                                text = "未拥有",
                                fontSize = 11.sp,
                                color = Color(0xFFFF5722), // 橙红色
                                fontWeight = FontWeight.Medium
                            )
                        } else {
                            // 已拥有只显示修炼状态
                            Text(
                                text = if (item.isUltimate) "已修炼" else "未修炼",
                                fontSize = 11.sp,
                                color = if (item.isUltimate) Color(0xFF4CAF50) else Color(0xFF9E9E9E),
                                fontWeight = if (item.isUltimate) FontWeight.Medium else FontWeight.Normal
                            )
                        }
                    }
                    Spacer(modifier = Modifier.height(4.dp))
                }
            }
            
            // 第四行：技能详情（仅菜地区显示）
            if (item is ChefResultWithSkills && !isLabArea) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 素材加成（含厨具+心法盘）
                    Text(
                        text = "素材:${item.materialGain}%",
                        fontSize = 11.sp,
                        color = if (item.materialGain > 0) Color(0xFF7B1FA2) else MaterialTheme.colorScheme.onSurfaceVariant,
                        fontWeight = if (item.materialGain > 0) FontWeight.Medium else FontWeight.Normal
                    )
                    
                    // 暴击素材（含厨具，厨具翻倍）
                    Text(
                        text = "暴击素材:${item.critMaterial}%",
                        fontSize = 11.sp,
                        color = if (item.critMaterial > 0) Color(0xFF1565C0) else MaterialTheme.colorScheme.onSurfaceVariant,
                        fontWeight = if (item.critMaterial > 0) FontWeight.Medium else FontWeight.Normal
                    )
                    
                    // 暴击率（含厨具，厨具不翻倍）
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text(
                            text = "暴击率:${item.critChance}%",
                            fontSize = 11.sp,
                            color = if (item.critChance > 0) Color(0xFFFF5722) else MaterialTheme.colorScheme.onSurfaceVariant,
                            fontWeight = if (item.critChance > 0) FontWeight.Medium else FontWeight.Normal
                        )
                        if (item is ChefResultWithSkills) {
                            Spacer(modifier = Modifier.width(2.dp))
                            Icon(
                                imageVector = Icons.Default.Info,
                                contentDescription = "查看暴击详情",
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier
                                    .size(14.dp)
                                    .clickable { showCritDetailsDialog = true }
                            )
                        }
                    }
                }
            }
            

        }
        
        // 右下角：拥有/修炼状态（非实验室地区）
        if (!isLabArea) {
            Row(
                modifier = Modifier.align(Alignment.BottomEnd),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                if (!item.owned) {
                    // 未拥有只显示拥有状态
                    Text(
                        text = "未拥有",
                        fontSize = 11.sp,
                        color = Color(0xFFFF5722), // 橙红色
                        fontWeight = FontWeight.Medium
                    )
                } else {
                    // 已拥有只显示修炼状态
                    Text(
                        text = if (item.isUltimate) "已修炼" else "未修炼",
                        fontSize = 11.sp,
                        color = if (item.isUltimate) Color(0xFF4CAF50) else Color(0xFF9E9E9E),
                        fontWeight = if (item.isUltimate) FontWeight.Medium else FontWeight.Normal
                    )
                }
            }
        }
    }
    
    // 显示采集点详情悬浮窗
    if (showCollectionDialog && item is ChefResultWithSkills) {
        CollectionDetailsDialog(
            chef = item,
            gameData = gameData,
            personalData = personalData,
            onDismiss = { showCollectionDialog = false }
        )
    }
    
    // 显示暴击详情悬浮窗
    if (showCritDetailsDialog && item is ChefResultWithSkills) {
        CritDetailsDialog(
            chef = item,
            gameData = gameData,
            personalData = personalData,
            onDismiss = { showCritDetailsDialog = false }
        )
    }
}

/**
 * 获取菜地区配置列表（按用户自定义顺序）
 */
private fun getVegAreaConfigs(settings: com.example.show_auto.data.SettingsStorage): List<VegAreaItem> {
    // 默认菜地区配置
    val defaultItems = listOf(
        VegAreaItem("池塘", "鱼", 29, 29, 5, 5),
        VegAreaItem("菜棚", "菜", 25, 25, 5, 5),
        VegAreaItem("菜地", "菜", 30, 30, 5, 5),
        VegAreaItem("森林", "菜", 32, 32, 5, 5),
        VegAreaItem("牧场", "肉", 25, 25, 5, 5),
        VegAreaItem("猪圈", "肉", 18, 18, 5, 5),
        VegAreaItem("鸡舍", "肉", 24, 24, 5, 5),
        VegAreaItem("作坊", "面", 26, 26, 5, 5)
    )
    
    // 加载已保存顺序，按顺序重新排列
    val savedOrder = settings.getVegAreaOrder()
    
    return if (savedOrder.isEmpty()) {
        // 如果没有保存的顺序，使用默认顺序
        defaultItems.map { item ->
            val savedPeople = settings.getVegAreaPeople(item.name)
            val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
            item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
        }
    } else {
        // 按保存的顺序重新排列，保留原有数据并加载保存的配置
        savedOrder.mapNotNull { savedName ->
            defaultItems.find { it.name == savedName }?.let { item ->
                val savedPeople = settings.getVegAreaPeople(item.name)
                val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
                item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
            }
        } + defaultItems.filter { item ->
            item.name !in savedOrder
        }.map { item ->
            val savedPeople = settings.getVegAreaPeople(item.name)
            val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
            item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
        }
    }
}

/**
 * 获取玉片区配置列表（按用户自定义顺序）
 */
private fun getJadeAreaConfigs(settings: com.example.show_auto.data.SettingsStorage): List<JadeAreaItem> {
    // 默认玉片区配置（根据地区要求设置双类型采集点）
    val defaultItems = listOf(
        JadeAreaItem("藏心亭", "肉", "菜", 60, 60, 5, 5),
        JadeAreaItem("朝阴山", "肉", "面", 60, 60, 5, 5),
        JadeAreaItem("北冥城", "鱼", "面", 60, 60, 5, 5),
        JadeAreaItem("清空谷", "肉", "鱼", 60, 60, 5, 5),
        JadeAreaItem("还寒洞", "菜", "面", 60, 60, 5, 5),
        JadeAreaItem("永昼宫", "菜", "鱼", 60, 60, 5, 5)
    )
    
    // 加载已保存顺序，按顺序重新排列
    val savedOrder = settings.getJadeAreaOrder()
    
    return if (savedOrder.isEmpty()) {
        // 如果没有保存的顺序，使用默认顺序
        defaultItems.map { item ->
            val savedPeople = settings.getJadeAreaPeople(item.name)
            val savedCapacity = settings.getJadeAreaCapacity(item.name, item.defaultCapacity)
            item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
        }
    } else {
        // 按保存的顺序重新排列，保留原有数据并加载保存的配置
        savedOrder.mapNotNull { savedName ->
            defaultItems.find { it.name == savedName }?.let { item ->
                val savedPeople = settings.getJadeAreaPeople(item.name)
                val savedCapacity = settings.getJadeAreaCapacity(item.name, item.defaultCapacity)
                item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
            }
        } + defaultItems.filter { item ->
            item.name !in savedOrder
        }.map { item ->
            val savedPeople = settings.getJadeAreaPeople(item.name)
            val savedCapacity = settings.getJadeAreaCapacity(item.name, item.defaultCapacity)
            item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
        }
    }
} 

/**
 * 获取调料区配置列表（按用户自定义顺序）
 */
private fun getCondAreaConfigs(settings: com.example.show_auto.data.SettingsStorage): List<CondItem> {
    // 默认调料区配置
    val defaultItems = listOf(
        CondItem("樊正阁", 5, 60),
        CondItem("庖丁阁", 5, 60),
        CondItem("膳祖阁", 5, 60),
        CondItem("易牙阁", 5, 60),
        CondItem("彭铿阁", 5, 60),
        CondItem("伊尹阁", 5, 60)
    )
    
    // 加载已保存顺序，按顺序重新排列
    val savedOrder = settings.getCondAreaOrder()
    
    return if (savedOrder.isEmpty()) {
        // 如果没有保存的顺序，使用默认顺序
        defaultItems.map { item ->
            val savedPeople = settings.getCondAreaPeople(item.name)
            val savedCapacity = settings.getCondAreaCapacity(item.name, item.currentCapacity)
            item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
        }
    } else {
        // 按保存的顺序重新排列，保留原有数据并加载保存的配置
        savedOrder.mapNotNull { savedName ->
            defaultItems.find { it.name == savedName }?.let { item ->
                val savedPeople = settings.getCondAreaPeople(item.name)
                val savedCapacity = settings.getCondAreaCapacity(item.name, item.currentCapacity)
                item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
            }
        } + defaultItems.filter { item ->
            item.name !in savedOrder
        }.map { item ->
            val savedPeople = settings.getCondAreaPeople(item.name)
            val savedCapacity = settings.getCondAreaCapacity(item.name, item.currentCapacity)
            item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
        }
    }
}

// 获取当前装备信息（无条件展示当前佩戴的厨具与已装配的全部心法盘名称）
private fun getCurrentEquipmentInfo(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?
): CurrentEquipmentInfo {
    return getCurrentEquipmentInfo(chef, gameData, personalData, false)
}

private fun getCurrentEquipmentInfo(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?,
    useSilverShoes: Boolean = false
): CurrentEquipmentInfo {
    if (gameData == null) return CurrentEquipmentInfo()
    
    val chefData = gameData.chefs.find { it.name == chef.chefName } ?: return CurrentEquipmentInfo()
    val personalChef = personalData?.chefs?.get(chefData.chefId) ?: return CurrentEquipmentInfo()
    
    // 显示实际使用的厨具名称（银布鞋逻辑下可能不是当前佩戴的厨具）
    val equipName = if (personalChef.equip != null) {
        val currentEquipId = personalChef.equip
        if (useSilverShoes) {
            // 银布鞋逻辑：如果是指定厨具ID则显示当前厨具，否则显示65号厨具
            if (currentEquipId in listOf(1088, 76, 77, 78, 64, 841)) {
                val equip = gameData.equips.find { it.equipId == currentEquipId.toString() }
                equip?.name ?: ""
            } else {
                // 显示65号厨具
                val silverShoes = gameData.equips.find { it.equipId == "65" }
                silverShoes?.name ?: ""
            }
        } else {
            // 原有逻辑：直接显示当前佩戴的厨具名称
            val equip = gameData.equips.find { it.equipId == currentEquipId.toString() }
            equip?.name ?: ""
        }
    } else if (useSilverShoes) {
        // 没有装备但银布鞋开启时，显示65号厨具
        val silverShoes = gameData.equips.find { it.equipId == "65" }
        silverShoes?.name ?: ""
    } else ""
    
    // 显示个人数据中已装配的绿色心法盘名称（type=2），并合并相同为 名称Xn
    val names = mutableListOf<String>()
    personalChef.ambers?.forEach { amberId ->
        if (amberId > 0) {
            val amber = gameData.ambers.find { it.amberId == amberId.toString() }
            if (amber != null && amber.type == 2) { // 只显示绿色心法盘
                names.add(amber.name)
            }
        }
    }
    val mergedAmberNames = names
        .groupingBy { it }
        .eachCount()
        .entries
        .sortedBy { it.key }
        .map { (name, count) -> if (count > 1) "${name}X${count}" else name }
    
    return CurrentEquipmentInfo(equipName, mergedAmberNames)
}

// 获取玉片区满级心法盘装备信息
private fun getJadeMaxLevelEquipmentInfo(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?,
    useSilverShoes: Boolean = false
): CurrentEquipmentInfo {
    if (gameData == null) return CurrentEquipmentInfo()
    
    val chefData = gameData.chefs.find { it.name == chef.chefName } ?: return CurrentEquipmentInfo()
    val personalChef = personalData?.chefs?.get(chefData.chefId) ?: return CurrentEquipmentInfo()
    
    // 获取厨具名称（与当前装备信息逻辑相同）
    val equipName = if (personalChef.equip != null) {
        val currentEquipId = personalChef.equip
        if (useSilverShoes) {
            if (currentEquipId in listOf(1088, 76, 77, 78, 64, 841)) {
                val equip = gameData.equips.find { it.equipId == currentEquipId.toString() }
                equip?.name ?: ""
            } else {
                val silverShoes = gameData.equips.find { it.equipId == "65" }
                silverShoes?.name ?: ""
            }
        } else {
            val equip = gameData.equips.find { it.equipId == currentEquipId.toString() }
            equip?.name ?: ""
        }
    } else if (useSilverShoes) {
        val silverShoes = gameData.equips.find { it.equipId == "65" }
        silverShoes?.name ?: ""
    } else ""
    
    // 获取玉片区使用的满级心法盘名称
    val greenAmberCount = extractGreenAmberCount(chefData.diskDesc)
    val amberNames = if (greenAmberCount > 0) {
        // 确定地区类型（从chef.chefArea推断）
        val areaType = when (chef.chefArea) {
            "藏心亭" -> "肉"  // 肉+鱼
            "朝阴山" -> "肉"  // 肉+菜  
            "北冥城" -> "肉"  // 肉+面
            "清空谷" -> "鱼"  // 鱼+菜
            "还寒洞" -> "鱼"  // 鱼+面
            "永昼宫" -> "菜"  // 菜+面
            else -> ""
        }
        
        if (areaType.isNotEmpty()) {
            // 找到该类型的最佳满级心法盘
            val maxLevel = when (chefData.rarity) {
                5 -> 5
                4 -> 4
                else -> 3
            }
            val bestAmber = CollectionTeamCalculator.findBestJadeAmberForType(gameData, areaType, maxLevel)
            if (bestAmber != null) {
                // 显示心法盘名称和数量
                if (greenAmberCount > 1) {
                    listOf("${bestAmber.name}X${greenAmberCount}")
                } else {
                    listOf(bestAmber.name)
                }
            } else {
                emptyList()
            }
        } else {
            emptyList()
        }
    } else {
        emptyList()
    }
    
    return CurrentEquipmentInfo(equipName, amberNames)
}

// 获取玉片区满级心法盘装备信息（用于素材详情）
private fun getJadeMaxLevelEquipmentInfoForMaterial(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?,
    useSilverShoes: Boolean = false
): CurrentEquipmentInfo {
    if (gameData == null) return CurrentEquipmentInfo()
    
    val chefData = gameData.chefs.find { it.name == chef.chefName } ?: return CurrentEquipmentInfo()
    val personalChef = personalData?.chefs?.get(chefData.chefId) ?: return CurrentEquipmentInfo()
    
    // 获取当前厨具名称（不使用理论最大值，保持实际装备）
    val equipName = if (personalChef.equip != null) {
        val currentEquipId = personalChef.equip
        if (useSilverShoes) {
            if (currentEquipId in listOf(1088, 76, 77, 78, 64, 841)) {
                val equip = gameData.equips.find { it.equipId == currentEquipId.toString() }
                equip?.name ?: ""
            } else {
                val silverShoes = gameData.equips.find { it.equipId == "65" }
                silverShoes?.name ?: ""
            }
        } else {
            val equip = gameData.equips.find { it.equipId == currentEquipId.toString() }
            equip?.name ?: ""
        }
    } else if (useSilverShoes) {
        val silverShoes = gameData.equips.find { it.equipId == "65" }
        silverShoes?.name ?: ""
    } else ""
    
    // 获取玉片区使用的满级心法盘名称（用于素材加成显示）
    val greenAmberCount = extractGreenAmberCount(chefData.diskDesc)
    val amberNames = if (greenAmberCount > 0) {
        // 确定地区类型（从chef.chefArea推断）
        val areaType = when (chef.chefArea) {
            "藏心亭" -> "肉"  // 肉+鱼
            "朝阴山" -> "肉"  // 肉+菜  
            "北冥城" -> "肉"  // 肉+面
            "清空谷" -> "鱼"  // 鱼+菜
            "还寒洞" -> "鱼"  // 鱼+面
            "永昼宫" -> "菜"  // 菜+面
            else -> ""
        }
        
        if (areaType.isNotEmpty()) {
            // 找到该类型的最佳满级素材加成心法盘（注意：这里用于素材加成，不是采集点）
            val maxLevel = when (chefData.rarity) {
                5 -> 5
                4 -> 4
                else -> 3
            }
            val bestAmber = CollectionTeamCalculator.findBestAmberForType(gameData, areaType, maxLevel)
            if (bestAmber != null) {
                // 显示心法盘名称和数量
                if (greenAmberCount > 1) {
                    listOf("${bestAmber.name}X${greenAmberCount}")
                } else {
                    listOf(bestAmber.name)
                }
            } else {
                emptyList()
            }
        } else {
            emptyList()
        }
    } else {
        emptyList()
    }
    
    return CurrentEquipmentInfo(equipName, amberNames)
}

// 获取理论最大值装备信息 - 与计算逻辑保持一致（仅展示采集点类心法盘，并合并名称Xn）
private fun getTheoreticalEquipmentInfo(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?,
    currentAreaType: String
): CurrentEquipmentInfo {
    return getTheoreticalEquipmentInfo(chef, gameData, personalData, currentAreaType, false)
}

private fun getTheoreticalEquipmentInfo(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?,
    currentAreaType: String,
    useSilverShoes: Boolean = false
): CurrentEquipmentInfo {
    if (gameData == null) return CurrentEquipmentInfo()
    
    val chefData = gameData.chefs.find { it.name == chef.chefName } ?: return CurrentEquipmentInfo()
    
    // 1. 获取理论计算时使用的厨具名称，并与当前佩戴对比后决定展示名
    val bestEquipNameRaw = getTheoreticalBestEquipName(chef, gameData, personalData, currentAreaType, useSilverShoes)
    val bestEquip = gameData.equips.find { it.name == bestEquipNameRaw }
    val personalChefForEquip = personalData?.chefs?.get(chefData.chefId)
    val currentEquipName = personalChefForEquip?.equip?.toString()?.let { id ->
        gameData.equips.find { it.equipId == id }?.name
    } ?: ""
    val equipName = if (bestEquip != null) {
        val usedName = bestEquip.name
        if (usedName == currentEquipName && currentEquipName.isNotEmpty()) currentEquipName else usedName
    } else ""
    
    // 2. 获取心法盘名称（与calculateMaxAmberBonusForType逻辑一致，仅采集点类）
    val amberNames = mutableListOf<String>()
    
    if (currentAreaType.isNotEmpty()) {
        val greenAmberCount = parseGreenAmberCount(chefData.diskDesc)
        if (greenAmberCount > 0) {
            val maxLevel = when (chef.chefRarity) {
                5 -> 5
                4 -> 4
                else -> 3
            }
            val bestAmber = findBestAmberForType(gameData, currentAreaType, maxLevel)
            if (bestAmber != null) {
                repeat(greenAmberCount) { amberNames.add(bestAmber.name) }
            }
        }
    }
    // 合并相同名称：名称Xn
    val mergedAmberNames = amberNames
        .groupingBy { it }
        .eachCount()
        .entries
        .sortedBy { it.key }
        .map { (name, count) -> if (count > 1) "${name}X${count}" else name }
    
    return CurrentEquipmentInfo(equipName, mergedAmberNames)
}

// 获取理论最佳厨具名称（与calculateBestEquipBonus逻辑一致）
private fun getTheoreticalBestEquipName(chef: ChefResultWithSkills, gameData: GameData, personalData: PersonalData?, currentAreaType: String): String {
    return getTheoreticalBestEquipName(chef, gameData, personalData, currentAreaType, false)
}

private fun getTheoreticalBestEquipName(chef: ChefResultWithSkills, gameData: GameData, personalData: PersonalData?, currentAreaType: String, useSilverShoes: Boolean): String {
    val chefData = gameData.chefs.find { it.name == chef.chefName }
    if (chefData != null && personalData != null) {
        val personalChef = personalData.chefs[chefData.chefId]
        
        if (useSilverShoes) {
            // 银布鞋逻辑
            if (personalChef != null && personalChef.equip != null) {
                val currentEquipId = personalChef.equip.toString()
                // 如果是指定厨具ID则使用，否则用65号厨具
                if (currentEquipId in listOf("1088", "76", "77", "78", "64", "841")) {
                    val equip = gameData.equips.find { it.equipId == currentEquipId }
                    if (equip != null) return equip.name
                }
            }
            // 没有装备或不是指定厨具，使用65号厨具
        } else {
            // 原有逻辑
            if (personalChef != null && personalChef.equip != null) {
                val currentEquipId = personalChef.equip.toString()
                // 若佩戴为 1088/76/77/78/64/841 之一，直接返回
                if (currentEquipId in listOf("1088", "76", "77", "78", "64", "841")) {
                    val equip = gameData.equips.find { it.equipId == currentEquipId }
                    if (equip != null) return equip.name
                } else {
                    // 否则检查该厨具对当前分配类型加成是否>2
                    val equip = gameData.equips.find { it.equipId == currentEquipId }
                    if (equip != null) {
                        val bonus = calculateEquipCollectionBonusByType(equip, gameData, currentAreaType)
                        if (bonus > 2) return equip.name
                        // 如果加成=2，则使用65号厨具进行计算
                    }
                }
            }
        }
    }
    
    // 否则默认使用65号厨具
    val defaultEquip = gameData.equips.find { it.equipId == "65" }
    return defaultEquip?.name ?: ""
}

// 寻找指定类型的最佳心法盘（与calculateMaxAmberBonusForType逻辑完全一致）
private fun findBestAmberForType(gameData: GameData, targetType: String, maxLevel: Int): com.example.show_auto.data.Amber? {
    var bestAmber: com.example.show_auto.data.Amber? = null
    var maxTotalBonus = 0
    
    // 遍历所有绿色心法盘，寻找该类型的最高总加成（基础+等级加成）
    gameData.ambers.forEach { amber ->
        if (amber.type == 2) { // 绿色心法盘
            amber.skill.forEach { skillId ->
                val skill = gameData.skills.find { it.skillId == skillId }
                skill?.let { skillObj ->
                    val desc = skillObj.desc
                    // 只匹配素材获得加成类型的心法盘（采集获得XX食材+%）
                    val isMatchingType = when (targetType) {
                        "肉" -> desc.contains("采集获得肉类食材") && desc.contains("%")
                        "鱼" -> desc.contains("采集获得鱼类食材") && desc.contains("%")
                        "菜" -> desc.contains("采集获得菜类食材") && desc.contains("%")
                        "面" -> desc.contains("采集获得加工类食材") && desc.contains("%")
                        else -> false
                    }
                    
                    if (isMatchingType) {
                        // 解析素材加成基础值
                        val baseBonus = extractMaterialBonusFromAmber(desc, targetType)
                        if (baseBonus > 0) {
                            // 计算最高等级的总加成（与calculateMaxAmberBonusForType逻辑一致）
                            val levelBonus = if (maxLevel > 1) amber.amplification * (maxLevel - 1) else 0
                            val totalBonus = baseBonus + levelBonus
                            
                            if (totalBonus > maxTotalBonus) {
                                maxTotalBonus = totalBonus
                                bestAmber = amber
                            }
                        }
                    }
                }
            }
        }
    }
    
    return bestAmber
}

// 确定技能描述对应的采集类型（与calculateMaxAmberBonusForType逻辑一致）
private fun determineSkillCollectionType(desc: String): String {
    return when {
        desc.contains("肉类") || desc.contains("Meat") || desc.contains("畜产") -> "肉"
        desc.contains("鱼类") || desc.contains("Fish") || desc.contains("水产") -> "鱼"
        desc.contains("菜类") || desc.contains("Veg") || desc.contains("素产") -> "菜"
        desc.contains("加工") || desc.contains("Creation") || desc.contains("加工类") -> "面"
        else -> ""
    }
}

// 获取最佳厨具名称
private fun getBestEquipName(chef: ChefResultWithSkills, gameData: GameData, personalData: PersonalData?): String {
    val chefData = gameData.chefs.find { it.name == chef.chefName }
    if (chefData != null && personalData != null) {
        val personalChef = personalData.chefs[chefData.chefId]
        if (personalChef != null && personalChef.equip != null) {
            val currentEquipId = personalChef.equip.toString()
            if (currentEquipId in listOf("64", "841")) {
                val equip = gameData.equips.find { it.equipId == currentEquipId }
                return equip?.name ?: ""
            }
        }
    }
    
    // 默认使用65号厨具
    val defaultEquip = gameData.equips.find { it.equipId == "65" }
    return defaultEquip?.name ?: ""
}

// 检查心法盘是否适用于指定地区类型
private fun isAmberSuitableForAreaType(amber: com.example.show_auto.data.Amber, areaType: String): Boolean {
    val desc = amber.desc.lowercase()
    return when (areaType) {
        "肉" -> desc.contains("肉")
        "鱼" -> desc.contains("鱼")
        "菜" -> desc.contains("菜") || desc.contains("蔬菜")
        "面" -> desc.contains("面") || desc.contains("创意")
        else -> false
    }
}

// 获取指定类型的最佳心法盘名称
private fun getBestAmberNameForType(targetType: String, gameData: GameData): String {
    val suitableAmbers = gameData.ambers.filter { isAmberSuitableForAreaType(it, targetType) }
    // 选择稀有度最高的心法盘
    val bestAmber = suitableAmbers.maxByOrNull { it.rarity }
    return bestAmber?.name ?: ""
}

// 计算厨具对指定采集类型的采集点加成（仅解析该类型的采集+X，不含百分号）
private fun calculateEquipCollectionBonusByType(equip: Equip, gameData: GameData, targetType: String): Int {
    var maxCollectionBonus = 0
    val typePrefix = when (targetType) {
        "鱼" -> listOf("水产采集+", "鱼类采集+")
        "肉" -> listOf("畜产采集+", "肉类采集+")
        "菜" -> listOf("素产采集+", "蔬菜采集+")
        "面" -> listOf("加工采集+", "面类采集+")
        else -> emptyList()
    }
    equip.skill.forEach { skillId ->
        val skill = gameData.skills.find { it.skillId == skillId }
        val desc = skill?.desc ?: return@forEach
        val isTypeMatch = typePrefix.any { prefix -> desc.contains(prefix) }
        val isGeneric = desc.contains("采集+") && !desc.contains("%") // 通用采集点加成（兜底）
        if ((isTypeMatch || isGeneric) && !desc.contains("%")) {
            val value = parseCollectionBonusFromDesc(desc)
            if (value > 0) maxCollectionBonus = maxOf(maxCollectionBonus, value)
        }
    }
    return maxCollectionBonus
}

private data class EquipCollectionBonus(
    val meat: Int = 0,
    val fish: Int = 0,
    val veg: Int = 0,
    val creation: Int = 0
)

// 按当前加成页同样的规则解析厨具采集点加成：支持"全采集+X"和单类型"肉类/水产/蔬菜/面类采集+X"
private fun calculateEquipBonusAllTypes(equip: Equip, gameData: GameData): EquipCollectionBonus {
    var meat = 0
    var fish = 0
    var veg = 0
    var creation = 0

    equip.skill.forEach { skillId ->
        val skill = gameData.skills.find { it.skillId == skillId } ?: return@forEach
        val desc = skill.desc
        val amount = parseCollectionBonusFromDesc(desc)
        if (amount <= 0) return@forEach
        when {
            desc.contains("全采集") -> {
                meat += amount
                fish += amount
                veg += amount
                creation += amount
            }
            desc.contains("肉类采集") || desc.contains("畜产采集") -> meat += amount
            desc.contains("水产采集") || desc.contains("鱼类采集") -> fish += amount
            desc.contains("蔬菜采集") || desc.contains("菜类采集") -> veg += amount
            desc.contains("面类采集") || desc.contains("加工采集") -> creation += amount
        }
    }

    return EquipCollectionBonus(meat, fish, veg, creation)
}

/**
 * 暴击详情弹窗
 */
@Composable
private fun CritDetailsDialog(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?,
    onDismiss: () -> Unit
) {
    // 暴击详情 - 玉片区禁用理论最大值切换
    var showTheoreticalMax by remember { mutableStateOf(false) }
    
    // 判断是否为玉片区
    val isJadeArea = chef.chefArea in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
    
    // 判断是否为菜地区，决定是否使用银布鞋逻辑
    val isVegArea = chef.chefArea in listOf("池塘", "牧场", "猪圈", "鸡舍", "菜棚", "菜地", "森林", "作坊")
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }
    val useSilverShoes = (isVegArea && settings.getUseSilverShoes()) || (isJadeArea && settings.getUseJadeSilverShoes())
    val useMaxLevelAmber = if (isVegArea) settings.getUseMaxLevelAmber() else if (isJadeArea) settings.getUseJadeMaxLevelAmber() else false
    
    Dialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(
            dismissOnBackPress = true,
            dismissOnClickOutside = true
        )
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
                .then(
                    if (!isJadeArea) {
                        Modifier.clickable(
                            indication = null,
                            interactionSource = remember { MutableInteractionSource() }
                        ) {
                            // 只有非玉片区才允许切换显示模式
                            showTheoreticalMax = !showTheoreticalMax
                        }
                    } else {
                        Modifier
                    }
                ),
            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
            shape = RoundedCornerShape(16.dp)
        ) {
                         Column(
                 modifier = Modifier.padding(16.dp),
                 verticalArrangement = Arrangement.spacedBy(12.dp)
             ) {
                 // 标题
                 Row(
                     modifier = Modifier.fillMaxWidth(),
                     verticalAlignment = Alignment.CenterVertically,
                     horizontalArrangement = Arrangement.SpaceBetween
                 ) {
                     Text(
                         text = "${chef.chefName} 素材详情",
                         fontSize = 16.sp,
                         fontWeight = FontWeight.Bold,
                         color = MaterialTheme.colorScheme.primary
                     )
                     
                     // 显示绿色心法盘数量
                     if (gameData != null) {
                         val chefData = gameData.chefs.find { it.name == chef.chefName }
                         if (chefData != null) {
                             val greenAmberCount = extractGreenAmberCount(chefData.diskDesc)
                             val displayText = if (greenAmberCount > 0) {
                                 "绿色心法盘X$greenAmberCount"
                             } else {
                                 "无绿色心法盘"
                             }
                             Text(
                                 text = displayText,
                                 fontSize = 12.sp,
                                 fontWeight = FontWeight.Normal,
                                 color = Color(0xFF4CAF50) // 绿色
                             )
                         }
                     }
                 }
                 
                 HorizontalDivider()
                 
                                 // 缓存理论最大值计算结果和当前装备信息
                val theoreticalMaxValues = remember(chef, gameData, personalData, useSilverShoes, useMaxLevelAmber) {
                    calculateTheoreticalMaxValues(chef, gameData, personalData, useSilverShoes)
                }
                
                val currentEquipInfo = remember(chef, gameData, personalData, useSilverShoes, useMaxLevelAmber) {
                    getCurrentEquipmentInfo(chef, gameData, personalData, useSilverShoes)
                }
                 
                 // 显示装备信息 - 使用与采集点详情相同的字体大小
                 val titleText = if (showTheoreticalMax) "理论最大" else "当前加成"
                // 当开启满级心法盘开关时，需要区分菜地区和玉片区的装备显示逻辑
                val (equipName, amberNames) = when {
                    showTheoreticalMax -> Pair(theoreticalMaxValues.equipName, theoreticalMaxValues.amberNames)
                    useMaxLevelAmber && isVegArea -> Pair(theoreticalMaxValues.equipName, theoreticalMaxValues.amberNames)
                    useMaxLevelAmber && isJadeArea -> {
                        // 玉片区满级心法盘：保持当前厨具，只显示满级心法盘
                        val jadeEquipInfo = getJadeMaxLevelEquipmentInfoForMaterial(chef, gameData, personalData, useSilverShoes)
                        Pair(jadeEquipInfo.equipName, jadeEquipInfo.amberNames)
                    }
                    else -> Pair(currentEquipInfo.equipName, currentEquipInfo.amberNames)
                }
                 
                 Row(
                     verticalAlignment = Alignment.CenterVertically,
                     modifier = Modifier.fillMaxWidth()
                 ) {
                     // 标题部分保持原字体大小
                     Text(
                         text = titleText,
                         fontSize = 12.sp,
                         fontWeight = FontWeight.Medium,
                         color = MaterialTheme.colorScheme.primary
                     )
                     
                     // 装备信息部分使用小字体
                     if (equipName.isNotEmpty() || amberNames.isNotEmpty()) {
                         Text(
                             text = " ",
                             fontSize = 12.sp,
                             color = MaterialTheme.colorScheme.primary
                         )
                         
                         val equipParts = mutableListOf<String>()
                         if (equipName.isNotEmpty()) {
                             equipParts.add("厨具：$equipName")
                         }
                         if (amberNames.isNotEmpty()) {
                             equipParts.add("心法盘：${amberNames.joinToString("、")}")
                         }
                         
                         Text(
                             text = equipParts.joinToString("｜"),
                             fontSize = 9.sp,
                             fontWeight = FontWeight.Normal,
                             color = MaterialTheme.colorScheme.primary,
                             maxLines = 1,
                             overflow = TextOverflow.Ellipsis,
                             modifier = Modifier.weight(1f)
                         )
                     }
                 }
                 
                 // 暴击详情内容
                 CritDetailsContent(
                     chef = chef,
                     gameData = gameData,
                     personalData = personalData,
                     showTheoreticalMax = showTheoreticalMax
                 )
            }
        }
    }
}

/**
 * 暴击详情内容
 */
@Composable
private fun CritDetailsContent(
    chef: ChefResultWithSkills,
    gameData: GameData?,
    personalData: PersonalData?,
    showTheoreticalMax: Boolean
) {
    // 判断是否为菜地区或玉片区，决定是否使用银布鞋逻辑
    val isVegArea = chef.chefArea in listOf("池塘", "牧场", "猪圈", "鸡舍", "菜棚", "菜地", "森林", "作坊")
    val isJadeArea = chef.chefArea in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }
    val useSilverShoes = (isVegArea && settings.getUseSilverShoes()) || (isJadeArea && settings.getUseJadeSilverShoes())
    val useMaxLevelAmber = if (isJadeArea) settings.getUseJadeMaxLevelAmber() else settings.getUseMaxLevelAmber()
    if (gameData == null) {
        Text(
            text = "数据加载中...",
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center
        )
        return
    }
    
    val chefData = gameData.chefs.find { it.name == chef.chefName }
    if (chefData == null) {
        Text(
            text = "厨师数据未找到",
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center
        )
        return
    }
    
         // 计算暴击详情数据 - 玉片区禁用理论最大值
         val effectiveShowTheoreticalMax = if (isJadeArea) false else showTheoreticalMax
         
                 val critDetails = remember(chef, gameData, personalData, effectiveShowTheoreticalMax, useSilverShoes, useMaxLevelAmber) {
            // 对于玉片区，固定选择双类型中的第一个；对于其他地区，使用原来的逻辑
            val currentAreaType = determineFirstAreaType(chef.chefArea)
    
            calculateCritDetails(chefData, gameData, personalData, currentAreaType, effectiveShowTheoreticalMax, useSilverShoes, useMaxLevelAmber, isJadeArea)
        }
    
         Column(
         verticalArrangement = Arrangement.spacedBy(12.dp)
     ) {
         // 素材加成 - 第一行
         CritDetailRow(
             title = "素材加成",
             skillValue = critDetails.materialGainSkill,
             equipValue = critDetails.materialGainEquip,
             amberValue = critDetails.materialGainAmber,
             total = critDetails.materialGainTotal,
             color = Color(0xFF7B1FA2)
         )
         
         // 暴击素材 - 第二行
         CritDetailRow(
             title = "暴击素材",
             skillValue = critDetails.critMaterialSkill,
             equipValue = critDetails.critMaterialEquip,
             amberValue = 0, // 暴击素材无心法盘加成
             total = critDetails.critMaterialTotal,
             color = Color(0xFF1565C0)
         )
         
         // 暴击率 - 第三行
         CritDetailRow(
             title = "暴击率",
             skillValue = critDetails.critChanceSkill,
             equipValue = critDetails.critChanceEquip,
             amberValue = 0, // 暴击率无心法盘加成
             total = critDetails.critChanceTotal,
             color = Color(0xFF2E7D32)
         )
     }
     
     HorizontalDivider()
     
     // 说明文字 - 玉片区显示不同提示
     Text(
         text = if (isJadeArea) {
             " "
         } else if (showTheoreticalMax) {
             "点击查看当前加成"
         } else {
             "点击查看理论最大加成"
         },
         fontSize = 10.sp,
         color = MaterialTheme.colorScheme.onSurfaceVariant,
         textAlign = TextAlign.Center,
         modifier = Modifier.fillMaxWidth(),
         maxLines = 1,
         overflow = TextOverflow.Ellipsis
     )
}

/**
 * 暴击详情行 - 完全匹配采集点详情的布局样式
 */
@Composable
private fun CritDetailRow(
    title: String,
    skillValue: Int,
    equipValue: Int,
    amberValue: Int,
    total: Int,
    color: Color
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                color = color.copy(alpha = 0.1f),
                shape = RoundedCornerShape(8.dp)
            )
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Start
    ) {
        // 类型标识
        Box(
            modifier = Modifier
                .size(26.dp)
                .background(
                    color = color,
                    shape = RoundedCornerShape(4.dp)
                ),
            contentAlignment = Alignment.Center
        ) {
            val typeSymbol = when (title) {
                "素材加成" -> "素材"
                "暴击素材" -> "爆量"
                "暴击率" -> "爆率"
                else -> "?"
            }
            Text(
                text = typeSymbol,
                fontSize = 10.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White
            )
        }
        
        Spacer(modifier = Modifier.width(8.dp))
        
                 // 数值显示 - 根据加成来源数量调整格式
         Row(
             verticalAlignment = Alignment.CenterVertically,
             horizontalArrangement = Arrangement.spacedBy(4.dp),
             modifier = Modifier.weight(1f)
         ) {
             // 构建来源详情文本
             val parts = mutableListOf<String>()
             if (skillValue > 0) parts.add("技能$skillValue")
             if (equipValue > 0) parts.add("厨具$equipValue")
             if (amberValue > 0) parts.add("心法盘$amberValue")
             
             when {
                 parts.isEmpty() -> {
                     // 无加成时只显示总值
                     Text(
                         text = "${total}%",
                         fontSize = 11.sp,
                         fontWeight = FontWeight.Bold,
                         color = if (total > 0) color else MaterialTheme.colorScheme.onSurfaceVariant,
                         maxLines = 1,
                         overflow = TextOverflow.Visible
                     )
                 }
                 title == "素材加成" -> {
                     // 素材加成：如果总值大于所有显示的分量之和，说明有心法盘等隐藏加成
                     val displayedSum = parts.sumOf { part ->
                         part.substringAfter("技能").substringAfter("厨具").substringAfter("心法盘").removeSuffix("%").toIntOrNull() ?: 0
                     }
                     
                     if (parts.size == 1 && total == displayedSum) {
                         // 只有一个来源且总值匹配
                         Text(
                             text = "${parts[0]}%",
                             fontSize = 11.sp,
                             fontWeight = FontWeight.Bold,
                             color = color,
                             maxLines = 1,
                             overflow = TextOverflow.Visible
                         )
                     } else {
                         // 多个来源或有隐藏加成
                         Text(
                             text = if (parts.size > 1) "${parts.joinToString(" + ")} = ${total}%" else "${total}%",
                             fontSize = 11.sp,
                             fontWeight = FontWeight.Bold,
                             color = color,
                             maxLines = 1,
                             overflow = TextOverflow.Visible
                         )
                     }
                 }
                 parts.size == 1 -> {
                     // 暴击类技能只有一个来源时，直接显示"来源X%"
                     Text(
                         text = "${parts[0]}%",
                         fontSize = 11.sp,
                         fontWeight = FontWeight.Bold,
                         color = color,
                         maxLines = 1,
                         overflow = TextOverflow.Visible
                     )
                 }
                 else -> {
                     // 暴击类技能多个来源时，只显示选中的那组数据（实际上不会进入这里，因为已经在calculateCritDetails中选择了）
                     Text(
                         text = "${parts[0]}%",
                         fontSize = 11.sp,
                         fontWeight = FontWeight.Bold,
                         color = color,
                         maxLines = 1,
                         overflow = TextOverflow.Visible
                     )
                 }
             }
         }
    }
}

/**
 * 暴击详情数据类
 */
private data class CritDetails(
    val materialGainSkill: Int = 0,
    val materialGainEquip: Int = 0,
    val materialGainAmber: Int = 0,
    val materialGainTotal: Int = 0,
    val critMaterialSkill: Int = 0,
    val critMaterialEquip: Int = 0,
    val critMaterialTotal: Int = 0,
    val critChanceSkill: Int = 0,
    val critChanceEquip: Int = 0,
    val critChanceTotal: Int = 0
)

/**
 * 计算暴击详情数据
 */
private fun calculateCritDetails(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    currentAreaType: String,
    showTheoreticalMax: Boolean
): CritDetails {
    return calculateCritDetails(chef, gameData, personalData, currentAreaType, showTheoreticalMax, false, false, false)
}

private fun calculateCritDetails(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    currentAreaType: String,
    showTheoreticalMax: Boolean,
    useSilverShoes: Boolean = false
): CritDetails {
    return calculateCritDetails(chef, gameData, personalData, currentAreaType, showTheoreticalMax, useSilverShoes, false, false)
}

private fun calculateCritDetails(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    currentAreaType: String,
    showTheoreticalMax: Boolean,
    useSilverShoes: Boolean = false,
    useMaxLevelAmber: Boolean = false,
    isJadeArea: Boolean = false
): CritDetails {
    // 如果是理论最大值，需要使用理论最佳装备
    val personalChef = personalData?.chefs?.get(chef.chefId)
    
    // 1. 计算技能加成（厨师技能+修炼技能）
    val skillBonus = calculateSkillOnlyBonus(chef, gameData, personalData, currentAreaType)
    
    // 2. 计算厨具加成
    val equipBonus = if (showTheoreticalMax) {
        calculateTheoreticalEquipBonus(chef, gameData, personalData, currentAreaType, useSilverShoes)
    } else {
        calculateCurrentEquipBonus(chef, gameData, personalData, useSilverShoes)
    }
    
    // 3. 计算心法盘加成（仅素材加成有心法盘）
    // 玉片区特殊逻辑：满级心法盘开启时，使用采集点加成心法盘，不应该有素材加成
    val amberBonus = if (isJadeArea && useMaxLevelAmber) {
        // 玉片区+满级心法盘：心法盘槽位已放采集点加成心法盘，不应该有素材加成
        0
    } else if (showTheoreticalMax || useMaxLevelAmber) {
        // 理论最大值或满级心法盘开关开启时，使用满级心法盘计算
        calculateTheoreticalAmberBonus(chef, gameData, personalData, currentAreaType)
    } else {
        // 使用当前实际心法盘
        calculateCurrentAmberBonus(chef, gameData, personalData, currentAreaType)
    }
    
    // 选择暴击率最高的那组数据
    val (finalCritMaterial, finalCritChance, critSource) = if (equipBonus.critChanceBonus > skillBonus.critChanceBonus) {
        // 厨具暴击率更高，使用厨具数据
        Triple(equipBonus.critMaterialBonus, equipBonus.critChanceBonus, "厨具")
    } else if (skillBonus.critChanceBonus > 0) {
        // 厨师暴击率更高或相等，使用厨师数据
        Triple(skillBonus.critMaterialBonus, skillBonus.critChanceBonus, "技能")
    } else {
        // 都没有暴击技能
        Triple(0, 0, "无")
    }
    
    return CritDetails(
        materialGainSkill = skillBonus.gainBonus,
        materialGainEquip = equipBonus.gainBonus,
        materialGainAmber = amberBonus,
        materialGainTotal = skillBonus.gainBonus + equipBonus.gainBonus + amberBonus,
        critMaterialSkill = if (critSource == "技能") finalCritMaterial else 0,
        critMaterialEquip = if (critSource == "厨具") finalCritMaterial else 0,
        critMaterialTotal = finalCritMaterial,
        critChanceSkill = if (critSource == "技能") finalCritChance else 0,
        critChanceEquip = if (critSource == "厨具") finalCritChance else 0,
        critChanceTotal = finalCritChance
    )
}

/**
 * 计算仅技能加成（厨师技能+修炼技能）
 */
private fun calculateSkillOnlyBonus(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    targetType: String
): com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus {
    // 使用现有的calculateChefSkillBonus函数，但排除厨具技能
    var critMaterialBonus = 0
    var critChanceBonus = 0
    var gainBonus = 0
    
    // 1. 处理厨师普通技能
    if (chef.skill > 0) {
        val skill = gameData.skills.find { it.skillId == chef.skill }
        if (skill != null) {
            val bonus = parseSkillBonusFromDesc(skill.desc)
            critMaterialBonus += bonus.critMaterialBonus
            critChanceBonus += bonus.critChanceBonus
            gainBonus += bonus.gainBonus
        }
    }
    
    // 2. 处理修炼技能
    val personalChef = personalData?.chefs?.get(chef.chefId)
    if (personalChef != null) {
        for (skillId in chef.getAllUltimateSkills()) {
            val skill = gameData.skills.find { it.skillId == skillId }
            if (skill != null) {
                val bonus = parseSkillBonusFromDesc(skill.desc)
                critMaterialBonus += bonus.critMaterialBonus
                critChanceBonus += bonus.critChanceBonus
                gainBonus += bonus.gainBonus
            }
        }
    }
    
    return com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus(
        critMaterialBonus = critMaterialBonus,
        critChanceBonus = critChanceBonus,
        gainBonus = gainBonus
    )
}

/**
 * 计算当前厨具加成
 */
private fun calculateCurrentEquipBonus(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?
): com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus {
    return calculateCurrentEquipBonus(chef, gameData, personalData, false)
}

private fun calculateCurrentEquipBonus(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    useSilverShoes: Boolean = false
): com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus {
    val personalChef = personalData?.chefs?.get(chef.chefId)
    val equipId = personalChef?.equip
    
    // 银布鞋逻辑：确定最终使用的厨具ID
    val finalEquipId = if (useSilverShoes) {
        if (equipId != null) {
            // 检查厨师当前装备是否为指定厨具ID
            val allowedEquipIds = listOf(1088, 76, 77, 78, 64, 841)
            if (equipId in allowedEquipIds) {
                equipId // 使用当前装备
            } else {
                65 // 默认使用65号厨具（银布鞋）
            }
        } else {
            65 // 没有装备时默认使用65号厨具（银布鞋）
        }
    } else {
        equipId // 使用原有逻辑
    }
    
    if (finalEquipId == null) {
        return com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus()
    }
    
    val equip = gameData.equips.find { it.equipId == finalEquipId.toString() }
    if (equip == null) {
        return com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus()
    }
    
    var critMaterialBonus = 0
    var critChanceBonus = 0
    var gainBonus = 0
    
    val hasDoublingSkill = chef.getAllUltimateSkills().any { it == 528 }
    
    equip.skill.forEach { skillId ->
        val skill = gameData.skills.find { it.skillId == skillId }
        if (skill != null) {
            val bonus = parseSkillBonusFromDesc(skill.desc)
            
            if (hasDoublingSkill) {
                // 翻倍技能：暴击素材翻倍，暴击率不翻倍，素材加成翻倍
                critMaterialBonus += bonus.critMaterialBonus * 2
                critChanceBonus += bonus.critChanceBonus  // 不翻倍
                gainBonus += bonus.gainBonus * 2
            } else {
                critMaterialBonus += bonus.critMaterialBonus
                critChanceBonus += bonus.critChanceBonus
                gainBonus += bonus.gainBonus
            }
        }
    }
    
    return com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus(
        critMaterialBonus = critMaterialBonus,
        critChanceBonus = critChanceBonus,
        gainBonus = gainBonus
    )
}

/**
 * 计算理论厨具加成
 */
private fun calculateTheoreticalEquipBonus(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    currentAreaType: String
): com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus {
    return calculateTheoreticalEquipBonus(chef, gameData, personalData, currentAreaType, false)
}

private fun calculateTheoreticalEquipBonus(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    currentAreaType: String,
    useSilverShoes: Boolean = false
): com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus {
         // 临时转换为ChefResultWithSkills类型
    val chefWithSkills = ChefResultWithSkills(
        chefName = chef.name,
        chefRarity = chef.rarity,
        chefTimeSeconds = 0,
        chefOwned = true,
        chefArea = "未知", // Chef类没有area属性，暂时用默认值
        critChance = 0,
        critMaterial = 0,
        materialGain = 0
    )
   // 使用与理论最大值计算相同的厨具选择逻辑
   val bestEquipName = getTheoreticalBestEquipName(chefWithSkills, gameData, personalData, currentAreaType, useSilverShoes)
    val bestEquip = gameData.equips.find { it.name == bestEquipName }
    
    if (bestEquip == null) {
        return com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus()
    }
    
    var critMaterialBonus = 0
    var critChanceBonus = 0
    var gainBonus = 0
    
    val hasDoublingSkill = chef.getAllUltimateSkills().any { it == 528 }
    
    bestEquip.skill.forEach { skillId ->
        val skill = gameData.skills.find { it.skillId == skillId }
        if (skill != null) {
            val bonus = parseSkillBonusFromDesc(skill.desc)
            
            if (hasDoublingSkill) {
                critMaterialBonus += bonus.critMaterialBonus * 2
                critChanceBonus += bonus.critChanceBonus
                gainBonus += bonus.gainBonus * 2
            } else {
                critMaterialBonus += bonus.critMaterialBonus
                critChanceBonus += bonus.critChanceBonus
                gainBonus += bonus.gainBonus
            }
        }
    }
    
    return com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus(
        critMaterialBonus = critMaterialBonus,
        critChanceBonus = critChanceBonus,
        gainBonus = gainBonus
    )
}

/**
 * 计算当前心法盘素材加成
 */
private fun calculateCurrentAmberBonus(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    targetType: String
): Int {
    val personalChef = personalData?.chefs?.get(chef.chefId) ?: return 0
    var totalBonus = 0
    
         // 遍历已装配的心法盘 - 使用与CollectionTeamCalculator相同的逻辑
     val diskLevel = (personalChef.dlv ?: 1).coerceAtLeast(1)
     personalChef.ambers?.forEach { amberId ->
         if (amberId > 0) {
             val amberData = gameData.ambers.find { it.amberId == amberId.toString() }
             if (amberData != null && amberData.type == 2) { // 只计算绿色心法盘
                 val levelBonusEach = if (diskLevel > 1) amberData.amplification * (diskLevel - 1) else 0
                 amberData.skill.forEach { skillId ->
                     val skill = gameData.skills.find { it.skillId == skillId }
                     if (skill != null) {
                         // 解析心法盘素材加成，只统计匹配目标类型的
                         val baseBonus = extractMaterialBonusFromAmber(skill.desc, targetType)
                         if (baseBonus > 0) {
                             val totalAdd = baseBonus + levelBonusEach
                             totalBonus += totalAdd
                         }
                     }
                 }
             }
         }
     }
    
    return totalBonus
}

/**
 * 计算理论心法盘素材加成
 */
private fun calculateTheoreticalAmberBonus(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?,
    targetType: String
): Int {
         val chefData = gameData.chefs.find { it.name == chef.name } ?: return 0
    val greenAmberCount = extractGreenAmberCount(chefData.diskDesc)
    
    
    
    if (greenAmberCount == 0) return 0
    
         // 找到该类型的最佳心法盘
     val maxLevel = when (chefData.rarity) {
         5 -> 5    // 5星厨师：5级
         4 -> 4    // 4星厨师：4级
         else -> 3 // 3星及以下：3级
     }
     val bestAmber = findBestAmberForType(gameData, targetType, maxLevel)
     
     
     
     if (bestAmber == null) return 0
     
     // 解析心法盘基础素材加成
     bestAmber.skill.forEach { skillId ->
         val skill = gameData.skills.find { it.skillId == skillId }
                 if (skill != null) {
                 val materialBonus = extractMaterialBonusFromAmber(skill.desc, targetType)
                 
         
                 
                 if (materialBonus > 0) {
                     // 计算单个心法盘的总加成：基础值 + (等级-1) * amplification
                     val levelBonusEach = if (maxLevel > 1) bestAmber.amplification * (maxLevel - 1) else 0
                     val singleAmberBonus = materialBonus + levelBonusEach
                     val totalResult = singleAmberBonus * greenAmberCount
                     
             
                     
                     return totalResult
                 }
             }
         }
     
     return 0
}

/**
 * 从技能描述中解析暴击相关加成
 */
private fun parseSkillBonusFromDesc(skillDesc: String): com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus {
    var critMaterialBonus = 0
    var critChanceBonus = 0
    var gainBonus = 0
    
    // 暴击类技能：支持多种格式
    val critPatterns = arrayOf(
        Regex("探索时有(\\d+)%概率额外获得(\\d+)%的?素材"),
        Regex("有(\\d+)%概率额外获得(\\d+)%素材"),
        Regex("(\\d+)%概率额外获得(\\d+)%素材")
    )
    
    for (pattern in critPatterns) {
        val critMatch = pattern.find(skillDesc)
        if (critMatch != null) {
            critChanceBonus = critMatch.groupValues[1].toInt()
            critMaterialBonus = critMatch.groupValues[2].toInt()
            break
        }
    }
    
         // 加成类技能：只计算"素材获得+X%"，不计算"全体*类素材获得+X%"
     val gainPattern = Regex("素材获得\\+(\\d+)%")
     val gainMatch = gainPattern.find(skillDesc)
     if (gainMatch != null) {
         gainBonus = gainMatch.groupValues[1].toInt()
 
     }
     
     // 全体*类素材获得技能不参与计算，因为它们影响的是素材获得概率，不是采集点加成
     val allTypePattern = Regex("全体.*类素材获得\\+(\\d+)%")
     val allTypeMatch = allTypePattern.find(skillDesc)
     if (allTypeMatch != null) {
 
     }
    
    return com.example.show_auto.utils.CollectionTeamCalculator.SkillBonus(
        critMaterialBonus = critMaterialBonus,
        critChanceBonus = critChanceBonus,
        gainBonus = gainBonus
    )
}

/**
 * 从心法盘技能描述中提取素材加成数值 - 使用与CollectionTeamCalculator相同的逻辑
 */
private fun extractMaterialBonusFromAmber(skillDesc: String, targetType: String): Int {
    return try {
        val regex = Regex("""采集获得.*?食材\+(\d+)%""")
        val matchResult = regex.find(skillDesc)
        if (matchResult != null) {
            val baseBonus = matchResult.groupValues[1].toInt()
            // 检查是否匹配目标类型
            val isMatchingType = when (targetType) {
                "肉" -> skillDesc.contains("采集获得肉类食材") || skillDesc.contains("肉类食材")
                "鱼" -> skillDesc.contains("采集获得鱼类食材") || skillDesc.contains("鱼类食材")
                "菜" -> skillDesc.contains("采集获得菜类食材") || skillDesc.contains("菜类食材")
                "面" -> skillDesc.contains("采集获得加工类食材") || skillDesc.contains("加工类食材")
                else -> false
            }
            if (isMatchingType) baseBonus else 0
        } else {
            0
        }
    } catch (e: Exception) {
        0
    }
}

/**
 * 提取厨师的绿色心法盘数量
 */
private fun extractGreenAmberCount(diskDesc: String): Int {
    
    
    // 解析格式如 "蓝|蓝|绿<br>最高5级" 中的绿色心法盘数量
    val colorPart = diskDesc.split("<br>")[0] // 取颜色部分：蓝|蓝|绿
    val colors = colorPart.split("|") // 分割每个颜色
    val greenCount = colors.count { it.trim() == "绿" } // 统计绿色数量
    
    
    return greenCount
}

/**
 * 从心法盘描述中提取红色心法盘数量
 */
private fun extractRedAmberCount(diskDesc: String): Int {
    // 解析格式如 "蓝|蓝|红<br>最高5级" 中的红色心法盘数量
    val colorPart = diskDesc.split("<br>")[0] // 取颜色部分：蓝|蓝|红
    val colors = colorPart.split("|") // 分割每个颜色
    val redCount = colors.count { it.trim() == "红" } // 统计红色数量
    
    return redCount
}

/**
 * 替换厨师弹窗
 */
@Composable
private fun ReplaceChefDialog(
    areaName: String,
    currentChefName: String,
    gameData: GameData,
    personalData: PersonalData?,
    combinationStorage: CombinationStorage,
    currentQueryResults: List<ChefResult>,
    onDismiss: () -> Unit,
    onReplaceChef: (ChefResult) -> Unit
) {
    // 控制是否只显示未分配的厨师
    var showOnlyUnassigned by remember { mutableStateOf(false) }
    // 控制是否查询全部厨师（包括未拥有的）
    var showAllChefs by remember { mutableStateOf(false) }
    var searchQuery by remember { mutableStateOf("") }
    
    // 判断是否为菜地区，决定是否使用银布鞋逻辑
    val isVegArea = areaName in listOf("池塘", "牧场", "猪圈", "鸡舍", "菜棚", "菜地", "森林", "作坊")
    val isJadeArea = areaName in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }
    val useSilverShoes = (isVegArea && settings.getUseSilverShoes()) || (isJadeArea && settings.getUseJadeSilverShoes())
    
    // 获取该地区的所有可用厨师 - 使用与一键查询相同的逻辑
    val availableChefs = remember(areaName, currentChefName, currentQueryResults.size, gameData.chefs.size, showOnlyUnassigned, showAllChefs, searchQuery, useSilverShoes, personalData) {
        // 获取已保存配置中的所有厨师
        val savedChefNames = combinationStorage.getAllCombinations()
            .flatMap { it.chefs.map { chef -> chef.name } }
            .toSet()
        
        // 获取当前地区已分配的厨师
        val currentAreaChefNames = currentQueryResults
            .filter { it.area == areaName }
            .map { it.name }
            .toSet()
        
        // 创建厨师分配映射表（厨师名 -> 地区名）
        val chefAreaMap = currentQueryResults.associate { it.name to it.area }
        
        // 过滤可用厨师（根据"查询全部"开关决定是否只显示已拥有的厨师）
        val baseFilteredChefs = if (showAllChefs) {
            // 查询全部厨师（包括未拥有的）
            gameData.chefs.filter { chef ->
                // 排除已保存配置中的厨师
                chef.name !in savedChefNames &&
                // 排除被替换的厨师本身（它不应该出现在自己的替换列表中）- 仅在替换模式下生效
                (currentChefName.isEmpty() || chef.name != currentChefName) &&
                // 排除当前地区的其他已分配厨师
                chef.name !in currentAreaChefNames &&
                // 根据"只查未分配"状态决定是否排除已分配给其他地区的厨师
                (!showOnlyUnassigned || chefAreaMap[chef.name] == null)
            }
        } else if (personalData != null) {
            // 只显示已拥有的厨师
            gameData.chefs.filter { chef ->
                // 只显示已拥有的厨师
                (personalData.chefs[chef.chefId]?.got == true) &&
                // 排除已保存配置中的厨师
                chef.name !in savedChefNames &&
                // 排除被替换的厨师本身（它不应该出现在自己的替换列表中）- 仅在替换模式下生效
                (currentChefName.isEmpty() || chef.name != currentChefName) &&
                // 排除当前地区的其他已分配厨师
                chef.name !in currentAreaChefNames &&
                // 根据"只查未分配"状态决定是否排除已分配给其他地区的厨师
                (!showOnlyUnassigned || chefAreaMap[chef.name] == null)
            }
        } else {
            // 没有个人数据时，不显示任何厨师
            emptyList()
        }
        
        // 判断是否为玉片区和实验室区
        val isJadeArea = areaName in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
        val isLabArea = areaName in listOf("蒸", "炸", "炒", "煮", "切", "烤")
        
        // 实验室区域额外过滤：基础技法值过滤
        val filteredChefs = if (isLabArea) {
            // 获取启用的光环厨师
            val enabledAuraChefs = getEnabledAuraChefs(gameData, personalData, settings, context)
            
            // 先尝试过滤基础技法值 >= 200 的厨师
            val highSkillChefs = baseFilteredChefs.filter { chef ->
                val baseSkillValue = when (areaName) {
                    "蒸" -> chef.steam
                    "炸" -> chef.fry
                    "炒" -> chef.stirfry
                    "煮" -> chef.boil
                    "切" -> chef.knife
                    "烤" -> chef.bake
                    else -> 0
                }
                
                // 基础技法值检查
                val skillValueCheck = baseSkillValue >= 200
                
                // 如果是光环厨师，额外检查技法类型匹配
                val auraCheck = if (chef.name in enabledAuraChefs) {
                    val (auraBonus, _) = getChefAuraBonusWithType(chef, gameData.skills, areaName)
                    auraBonus > 0 // 只有光环加成大于0才算匹配
                } else {
                    true // 非光环厨师不需要额外检查
                }
                
                skillValueCheck && auraCheck
            }
            
            // 如果过滤后的厨师少于5个，降低要求到基础技法值 >= 100
            if (highSkillChefs.size < 5) {
                baseFilteredChefs.filter { chef ->
                    val baseSkillValue = when (areaName) {
                        "蒸" -> chef.steam
                        "炸" -> chef.fry
                        "炒" -> chef.stirfry
                        "煮" -> chef.boil
                        "切" -> chef.knife
                        "烤" -> chef.bake
                        else -> 0
                    }
                    
                    // 基础技法值检查
                    val skillValueCheck = baseSkillValue >= 100
                    
                    // 如果是光环厨师，额外检查技法类型匹配
                    val auraCheck = if (chef.name in enabledAuraChefs) {
                        val (auraBonus, _) = getChefAuraBonusWithType(chef, gameData.skills, areaName)
                        auraBonus > 0 // 只有光环加成大于0才算匹配
                    } else {
                        true // 非光环厨师不需要额外检查
                    }
                    
                    skillValueCheck && auraCheck
                }
            } else {
                highSkillChefs
            }
        } else {
            baseFilteredChefs
        }
        
        // 转换为ChefResultWithSkills格式，使用与一键查询相同的计算逻辑
        val chefsWithSkills = filteredChefs.map { chef ->
            // 根据地区名称确定采集类型（与一键查询逻辑保持一致）
            val targetType = when (areaName) {
                "池塘" -> "鱼"
                "牧场", "猪圈", "鸡舍" -> "肉"
                "菜棚", "菜地", "森林" -> "菜"
                "作坊" -> "面"
                "藏心亭" -> "肉"
                "朝阴山" -> "肉"
                "北冥城" -> "鱼"
                "清空谷" -> "肉"
                "还寒洞" -> "菜"
                "永昼宫" -> "菜"
                else -> ""
            }
            
            // 计算技能加成信息（与一键查询逻辑保持一致）
            val separatedSkills = CollectionTeamCalculator.calculateSeparatedSkillBonus(
                chef, gameData, personalData, targetType, useSilverShoes, settings.getUseMaxLevelAmber(), isJadeArea, settings.getUseAllUltimateTraining()
            )
            
            // 计算采集点数值（使用与一键查询相同的计算逻辑，包含厨具和心法盘加成）
            val collectionStats = CollectionTeamCalculator.calculateChefCollectionStats(
                chef, gameData, personalData, useSilverShoes, settings.getUseMaxLevelAmber(), "", isJadeArea, settings.getUseAllUltimateTraining()
            )
            val totalMeat = collectionStats.meat
            val totalFish = collectionStats.fish
            val totalVeg = collectionStats.veg
            val totalCreation = collectionStats.creation
            
            // 根据地区类型确定显示格式
            val collectionDetails = if (isLabArea) {
                // 实验室区域显示技法值
                val skillType = areaName // 技法类型就是地区名（蒸、炸、炒、煮、切、烤）
                
                // 计算该厨师在指定技法类型的技法值
                val skillStats = CollectionTeamCalculator.calculateChefSkillStats(
                    chef = chef,
                    gameData = gameData,
                    personalData = personalData,
                    useLabEquip150 = settings.getUseLabEquip150(),
                    useBeginnerEquip100 = settings.getUseBeginnerEquip100(),
                    useMaxLevelAmber = settings.getUseMaxLevelAmber(),
                    context = context,
                    useAllUltimateTraining = settings.getUseAllUltimateTraining(),
                    targetSkillType = skillType
                )
                
                val skillValue = skillStats.getSkillValue(skillType)
                
                // 构建技法值详细信息，包含光环信息
                val detailsBuilder = StringBuilder()
                detailsBuilder.append("${skillType}技法值: $skillValue")
                
                // 获取当前用户启用的光环厨师
                val enabledAuraChefs = getEnabledAuraChefs(gameData, personalData, settings, context)
                
                // 如果是光环厨师，添加光环信息
                if (chef.name in enabledAuraChefs) {
                    // 获取光环技能加成值和类型
                    val (auraBonus, auraType) = getChefAuraBonusWithType(chef, gameData.skills, skillType)
                    if (auraBonus > 0) {
                        // 根据光环类型决定乘数
                        val (multiplier, multiplierDesc) = when (auraType) {
                            "下位上场厨师" -> Pair(1, "X1")
                            "场上所有厨师" -> {
                                val chefCount = 5 // 实验室固定5人
                                Pair(chefCount, "X$chefCount")
                            }
                            else -> Pair(1, "X1")
                        }
                        val totalAuraBonus = auraBonus * multiplier
                        detailsBuilder.append("（光环：${skillType}+${auraBonus} ${multiplierDesc} = ${totalAuraBonus}）")
                    }
                }
                
                detailsBuilder.toString()
            } else if (isJadeArea) {
                // 玉片区显示双类型采集点总和
                val dualTypeTotal = when (areaName) {
                    "藏心亭" -> totalMeat + totalVeg
                    "朝阴山" -> totalMeat + totalCreation
                    "北冥城" -> totalFish + totalCreation
                    "清空谷" -> totalMeat + totalFish
                    "还寒洞" -> totalVeg + totalCreation
                    "永昼宫" -> totalVeg + totalFish
                    else -> 0
                }
                
                val dualTypeDescription = when (areaName) {
                    "藏心亭" -> "肉+菜:$dualTypeTotal"
                    "朝阴山" -> "肉+面:$dualTypeTotal"
                    "北冥城" -> "鱼+面:$dualTypeTotal"
                    "清空谷" -> "肉+鱼:$dualTypeTotal"
                    "还寒洞" -> "菜+面:$dualTypeTotal"
                    "永昼宫" -> "菜+鱼:$dualTypeTotal"
                    else -> ""
                }
                dualTypeDescription
            } else {
                // 菜地区显示四种类型采集点
                "肉:${totalMeat} 鱼:${totalFish} 菜:${totalVeg} 面:${totalCreation}"
            }
            
            ChefResultWithSkills(
                chefName = chef.name,
                chefRarity = chef.rarity,
                chefTimeSeconds = 0, // 替换时不关心时间效率
                chefOwned = personalData?.chefs?.get(chef.chefId)?.got ?: false,
                chefArea = areaName,
                chefCollectionDetails = collectionDetails,
                chefIsUltimate = chef.ult,
                critChance = separatedSkills.totalCritChance,
                critMaterial = separatedSkills.totalCritMaterial,
                materialGain = separatedSkills.totalMaterialGain,
                baseMeat = chef.meat,
                baseFish = chef.fish,
                baseVeg = chef.veg,
                baseCreation = chef.creation,
                totalMeat = totalMeat,
                totalFish = totalFish,
                totalVeg = totalVeg,
                totalCreation = totalCreation
            )
        }.filter { chefResult ->
            // 过滤掉在该地区类型采集点为0的厨师
            val targetCollectionValue = when (areaName) {
                "池塘" -> chefResult.totalFish
                "牧场", "猪圈", "鸡舍" -> chefResult.totalMeat
                "菜棚", "菜地", "森林" -> chefResult.totalVeg
                "作坊" -> chefResult.totalCreation
                "藏心亭" -> chefResult.totalMeat + chefResult.totalVeg
                "朝阴山" -> chefResult.totalMeat + chefResult.totalCreation
                "北冥城" -> chefResult.totalFish + chefResult.totalCreation
                "清空谷" -> chefResult.totalMeat + chefResult.totalFish
                "还寒洞" -> chefResult.totalVeg + chefResult.totalCreation
                "永昼宫" -> chefResult.totalVeg + chefResult.totalFish
                else -> 1 // 默认不过滤
            }
            targetCollectionValue > 0
        }
        
        // 使用与一键查询相同的排序逻辑
        val sortedChefs = if (isJadeArea) {
            // 玉片区按双采集点数值排序（由高到低）
            chefsWithSkills.sortedByDescending { chef ->
                when (areaName) {
                    "藏心亭" -> chef.totalMeat + chef.totalVeg
                    "朝阴山" -> chef.totalMeat + chef.totalCreation
                    "北冥城" -> chef.totalFish + chef.totalCreation
                    "清空谷" -> chef.totalMeat + chef.totalFish
                    "还寒洞" -> chef.totalVeg + chef.totalCreation
                    "永昼宫" -> chef.totalVeg + chef.totalFish
                    else -> 0
                }
            }
        } else if (isLabArea) {
            // 实验室区域按技法值+光环总加成值降序排列
            chefsWithSkills.sortedByDescending { chef ->
                // 从collectionDetails字符串中提取技法值
                val skillValueRegex = """技法值: (\d+)""".toRegex()
                val skillValueMatch = skillValueRegex.find(chef.chefCollectionDetails)
                val skillValue = skillValueMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
                
                // 从collectionDetails字符串中提取光环总加成值（已经乘以人数的值）
                val auraTotalRegex = """X5 = (\d+)）""".toRegex()
                val auraTotalMatch = auraTotalRegex.find(chef.chefCollectionDetails)
                val auraTotalBonus = auraTotalMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
                
                val totalValue = skillValue + auraTotalBonus
                println("替换页面排序调试 - ${chef.name}: 技法值=$skillValue, 光环总加成=$auraTotalBonus, 总值=$totalValue")
                println("  详情字符串: ${chef.chefCollectionDetails}")
                
                // 返回技法值+光环总加成值的总和
                totalValue
            }
        } else {
            // 菜地区使用与一键查询完全相同的排序逻辑
            val targetType = when (areaName) {
                "池塘" -> "鱼"
                "牧场", "猪圈", "鸡舍" -> "肉"
                "菜棚", "菜地", "森林" -> "菜"
                "作坊" -> "面"
                else -> ""
            }
            
            // 使用与一键查询完全相同的排序逻辑
            // 优先级：智能技能评分 > 专长匹配 > 绿色心法盘数量+采集点 > 其他采集点
            chefsWithSkills.sortedWith(
                compareBy<ChefResultWithSkills> { chef -> 
                    // 保护：稀有客人/开业时间技能厨师永不使用（与一键查询逻辑一致）
                    if (chef.critChance > 0 && chef.materialGain == 0) 1 else 0 
                }
                .thenByDescending { chef -> 
                    // 智能技能评分（与一键查询逻辑一致）
                    val skillBonus = chef.materialGain + chef.critMaterial + chef.critChance
                    val isTopTier = chef.materialGain > 0 || chef.critChance > 30
                    
                    if (isTopTier) {
                        // 最高优先级：有素材加成 或 暴击率>30%
                        val typeBonus = 10000.0
                        val critChanceScore = chef.critChance * 1000.0
                        val critMaterialScore = chef.critMaterial * 100.0
                        val gainScore = chef.materialGain * 1.0
                        typeBonus + critChanceScore + critMaterialScore + gainScore
                    } else {
                        // 次级优先级：其他情况
                        val gainScore = chef.materialGain * 1.0
                        val critScore = if (chef.critMaterial > 0 || chef.critChance > 0) {
                            if (chef.critChance <= 10) {
                                (chef.critMaterial * 0.3 + chef.critChance * 0.2)
                            } else {
                                chef.critMaterial * 0.8 + chef.critChance * 0.6
                            }
                        } else {
                            0.0
                        }
                        
                        val typeBonus = when {
                            chef.critChance > 10 && chef.critChance <= 30 && chef.materialGain == 0 -> 500.0
                            chef.critChance <= 10 && chef.critChance > 0 && chef.materialGain == 0 -> 100.0
                            else -> 0.0
                        }
                        
                        typeBonus + gainScore + critScore
                    }
                }
                .thenByDescending { chef -> 
                    // 专长匹配（与一键查询逻辑一致）
                    when (targetType) {
                        "鱼" -> chef.baseFish
                        "肉" -> chef.baseMeat
                        "菜" -> chef.baseVeg
                        "面" -> chef.baseCreation
                        else -> 0
                    }
                }
                .thenByDescending { chef -> 
                    // 绿色心法盘数量+采集点（与一键查询逻辑一致）
                    // 这里需要从chef的diskDesc中获取绿色心法盘数量
                    val greenAmberCount = chef.chefArea.let { area ->
                        // 临时方案：根据地区类型判断，实际应该从chef.diskDesc解析
                        when (area) {
                            "菜地" -> 1 // 示例值，实际应该从chef.diskDesc解析
                            else -> 0
                        }
                    }
                    greenAmberCount * 10 + when (targetType) {
                        "鱼" -> chef.totalFish
                        "肉" -> chef.totalMeat
                        "菜" -> chef.totalVeg
                        "面" -> chef.totalCreation
                        else -> 0
                    }
                }
                .thenBy { chef ->
                    // 其他采集点（与一键查询逻辑一致）
                    val total = chef.totalMeat + chef.totalFish + chef.totalVeg + chef.totalCreation
                    val targetValue = when (targetType) {
                        "鱼" -> chef.totalFish
                        "肉" -> chef.totalMeat
                        "菜" -> chef.totalVeg
                        "面" -> chef.totalCreation
                        else -> 0
                    }
                    total - targetValue
                }
            )
        }
        
        // 根据搜索查询过滤厨师
        sortedChefs.filter { chef ->
            if (searchQuery.isBlank()) {
                true
            } else {
                chef.chefName.contains(searchQuery, ignoreCase = true)
            }
        }
    }

    Dialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true)
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.8f),
            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
            shape = RoundedCornerShape(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                // 标题
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            text = if (currentChefName.isEmpty()) "选择 - $areaName" else "替换 - $areaName",
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.width(8.dp))
                        
                        // 查未分配按钮
                        Button(
                            onClick = { showOnlyUnassigned = !showOnlyUnassigned },
                            modifier = Modifier
                                .height(24.dp)
                                .width(45.dp),
                            contentPadding = PaddingValues(horizontal = 2.dp, vertical = 0.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = if (showOnlyUnassigned) Color(0xFF1976D2) else Color(0xFFE3F2FD),
                                contentColor = if (showOnlyUnassigned) Color.White else Color.Black
                            ),
                            shape = RoundedCornerShape(6.dp)
                        ) {
                            Text(
                                text = "查未分配",
                                fontSize = 8.sp
                            )
                        }
                        
                        Spacer(modifier = Modifier.width(2.dp))
                        
                        // 查询全部按钮
                        Button(
                            onClick = { showAllChefs = !showAllChefs },
                            modifier = Modifier
                                .height(24.dp)
                                .width(45.dp),
                            contentPadding = PaddingValues(horizontal = 2.dp, vertical = 0.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = if (showAllChefs) Color(0xFF1976D2) else Color(0xFFE3F2FD),
                                contentColor = if (showAllChefs) Color.White else Color.Black
                            ),
                            shape = RoundedCornerShape(6.dp)
                        ) {
                            Text(
                                text = "查询全部",
                                fontSize = 8.sp
                            )
                        }
                    }
                    
                    IconButton(onClick = onDismiss) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = "关闭",
                            tint = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
                
                // 获取当前厨师的技能信息
                val currentChef = currentQueryResults.find { it.name == currentChefName }
                
                // 获取当前厨师的技能信息并放在一行显示（仅在替换模式下显示）
                if (currentChefName.isNotEmpty() && currentChef is ChefResultWithSkills) {
                    // 在这里重新定义isLabArea以确保作用域正确
                    val isLabAreaForDisplay = areaName in listOf("蒸", "炸", "炒", "煮", "切", "烤")
                    val annotatedText = buildAnnotatedString {
                        withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.onSurfaceVariant)) {
                            if (isLabAreaForDisplay) {
                                // 实验室区域只显示厨师名字
                                append("当前厨师：$currentChefName")
                            } else {
                                // 其他区域显示素材信息
                                append("当前厨师：$currentChefName ｜素材:${currentChef.materialGain}% 暴量:${currentChef.critMaterial}% ")
                            }
                        }
                        if (!isLabAreaForDisplay) {
                            withStyle(style = SpanStyle(color = Color(0xFFFF5722))) {
                                append("暴率:${currentChef.critChance}%")
                            }
                        }
                    }
                    Text(
                        text = annotatedText,
                        fontSize = 11.sp,
                        modifier = Modifier.padding(bottom = 16.dp)
                    )
                } else if (currentChefName.isNotEmpty()) {
                    Text(
                        text = "当前：$currentChefName",
                        fontSize = 11.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(bottom = 16.dp)
                    )
                }
                
                // 搜索框
                OutlinedTextField(
                    value = searchQuery,
                    onValueChange = { searchQuery = it },
                    label = { Text("搜索厨师名字") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp),
                    singleLine = true,
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索"
                        )
                    },
                    trailingIcon = {
                        if (searchQuery.isNotEmpty()) {
                            IconButton(onClick = { searchQuery = "" }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清除"
                                )
                            }
                        }
                    }
                )
                
                if (availableChefs.isEmpty()) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = if (searchQuery.isNotEmpty()) "未找到匹配的厨师" else "暂无可替换的厨师",
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                } else {
                    LazyColumn {
                        items(availableChefs) { chef ->
                                                         Card(
                                 modifier = Modifier
                                     .fillMaxWidth()
                                     .padding(vertical = 2.dp)
                                     .clickable { onReplaceChef(chef) },
                                 colors = CardDefaults.cardColors(
                                     containerColor = Color(0xFFE3F2FD) // 淡蓝色
                                 ),
                                 elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                             ) {
                                ChefResultRow(
                                    item = chef,
                                    gameData = gameData,
                                    personalData = personalData,
                                    currentQueryResults = currentQueryResults,
                                    isInReplaceDialog = true
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

/**
 * 保存成功提示弹窗
 */
@Composable
private fun SaveSuccessDialog(
    onDismiss: () -> Unit
) {
    // 1秒后自动消失
    LaunchedEffect(Unit) {
        delay(700)
        onDismiss()
    }
    
    Dialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(
            dismissOnBackPress = false,
            dismissOnClickOutside = false
        )
    ) {
        Card(
            modifier = Modifier
                .wrapContentSize()
                .padding(16.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color(0xFFE8F5E8) // 淡绿色背景
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
            shape = RoundedCornerShape(12.dp)
        ) {
            Row(
                modifier = Modifier.padding(16.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 成功图标
                Box(
                    modifier = Modifier
                        .size(32.dp)
                        .background(
                            color = Color(0xFF4CAF50),
                            shape = CircleShape
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Default.Check,
                        contentDescription = "成功",
                        tint = Color.White,
                        modifier = Modifier.size(18.dp)
                    )
                }
                
                Spacer(modifier = Modifier.width(12.dp))
                
                // 成功文字
                Text(
                    text = "保存成功",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF2E7D32)
                )
            }
        }
    }
}

/**
 * 已保存组合配置列表弹窗
 */
@Composable
private fun SavedCombinationsDialog(
    combinationStorage: CombinationStorage,
    onSelectCombination: (SavedCombination) -> Unit,
    onDismiss: () -> Unit,
    onReturnFromSchemeLoad: (() -> Unit)? = null, // 从方案加载后返回的回调
    refreshTrigger: Int = 0 // 用于触发数据刷新的计数器
) {
    val context = LocalContext.current
    val schemeStorage = remember { SchemeStorage(context) }
    
    var combinations by remember { mutableStateOf<List<SavedCombination>>(emptyList()) }
    var selectedCombinations by remember { mutableStateOf<Set<String>>(emptySet()) }
    // 每个区域独立的全选状态
    var areaSelectionStates by remember { mutableStateOf<Map<String, Set<String>>>(emptyMap()) }
    var showBatchDeleteDialog by remember { mutableStateOf(false) }
    var showSaveSchemeDialog by remember { mutableStateOf(false) }
    var showSchemesDialog by remember { mutableStateOf(false) }
    var showSchemesForMergeDialog by remember { mutableStateOf(false) }
    var showConflictDialog by remember { mutableStateOf(false) }
    var showActionChoiceDialog by remember { mutableStateOf(false) }
    var showAreaConflictDialog by remember { mutableStateOf(false) }
    var conflictChefs by remember { mutableStateOf<List<String>>(emptyList()) }
    var conflictAreas by remember { mutableStateOf<List<String>>(emptyList()) }
    var targetScheme by remember { mutableStateOf<Scheme?>(null) }
    // 配置页面始终显示四个区域，不受开关影响
    val safeAreas = listOf("玉片区", "菜地区", "调料区", "实验室")
    
    // 默认选择菜地区（索引为1）
    var selectedTabIndex by remember { mutableStateOf(1) } // 默认选择菜地区
    
    // 监听用户切换，当用户切换时刷新组合列表
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId()) }
    
    LaunchedEffect(refreshTrigger, currentUserId) {
        combinations = combinationStorage.getAllCombinations()
    }
    
    // 监听用户ID变化
    LaunchedEffect(Unit) {
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId()
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 用户切换了，刷新组合列表
                combinations = combinationStorage.getAllCombinations()
            }
            delay(500) // 每500毫秒检查一次
        }
    }
    
    // 批量删除确认弹窗
    if (showBatchDeleteDialog) {
        val selectedCombinationsList = combinations.filter { it.id in selectedCombinations }
        AlertDialog(
            onDismissRequest = { showBatchDeleteDialog = false },
            title = { Text("确认批量删除") },
            text = { 
                Column {
                    Text("确定要删除以下 ${selectedCombinationsList.size} 个组合配置吗？")
                    Spacer(modifier = Modifier.height(8.dp))
                    selectedCombinationsList.forEach { combination ->
                        Text(
                            text = "• ${combination.areaName}",
                            fontSize = 12.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        // 批量删除选中的组合
                        selectedCombinations.forEach { combinationId ->
                            combinationStorage.deleteCombination(combinationId)
                        }
                        // 刷新数据
                        combinations = combinationStorage.getAllCombinations()
                        // 清空选择状态
                        selectedCombinations = emptySet()
                        areaSelectionStates = emptyMap()
                        showBatchDeleteDialog = false
                    }
                ) {
                    Text("确认删除", color = MaterialTheme.colorScheme.error)
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { showBatchDeleteDialog = false }
                ) {
                    Text("取消")
                }
            }
        )
    }
    
    // 根据区域分类组合（移除重复的区域列表构建，使用上面已构建的safeAreas）
    
    // 定义每个区域包含的地点
    val getAreaType = { areaName: String ->
        when {
            areaName in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫") -> "玉片区"
            areaName in listOf("池塘", "牧场", "猪圈", "鸡舍", "作坊", "菜棚", "菜地", "森林") -> "菜地区"
            areaName in listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁") -> "调料区"
            areaName in listOf("蒸", "炸", "炒", "煮", "切", "烤") -> "实验室"
            else -> "菜地区" // 默认归类到菜地区
        }
    }
    
    // 按当前选中的标签过滤组合
    val selectedArea = if (selectedTabIndex < safeAreas.size) safeAreas[selectedTabIndex] else safeAreas.firstOrNull() ?: "菜地区"
    val filteredCombinations = combinations.filter { getAreaType(it.areaName) == selectedArea }
    
    // 当切换区域时，更新当前区域的选择状态显示
    LaunchedEffect(selectedArea) {
        // 切换区域时，确保当前区域的选择状态正确显示
        val currentAreaSelections = areaSelectionStates[selectedArea] ?: emptySet()
        // 不需要重置selectedCombinations，因为它是全局的，但需要确保UI正确显示
    }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { 
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text("已保存组合配置", fontSize = 18.sp, fontWeight = FontWeight.Bold)
                OutlinedButton(
                    onClick = { showSchemesDialog = true },
                    modifier = Modifier.height(32.dp),
                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 2.dp)
                ) {
                    Text("查看方案", fontSize = 12.sp)
                }
            }
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 500.dp)
            ) {
                // 三段切换标签
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    shape = RoundedCornerShape(20.dp),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Row(modifier = Modifier.padding(4.dp)) {
                        safeAreas.forEachIndexed { index, area ->
                            val selected = selectedTabIndex == index
                            Surface(
                                onClick = { selectedTabIndex = index },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(28.dp),
                                shape = RoundedCornerShape(16.dp),
                                color = if (selected) MaterialTheme.colorScheme.primary else Color.Transparent
                            ) {
                                Box(
                                    modifier = Modifier.fillMaxSize(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = area,
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium,
                                        color = if (selected) Color.White else MaterialTheme.colorScheme.primary
                                    )
                                }
                            }
                            if (index < safeAreas.lastIndex) Spacer(modifier = Modifier.width(4.dp))
                        }
                    }
                }
                
                if (filteredCombinations.isEmpty()) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text("该区域暂无保存的组合配置", color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                } else {
                    LazyColumn(
                        modifier = Modifier.padding(8.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        items(filteredCombinations) { combination ->
                            Card(
                                modifier = Modifier.fillMaxWidth(),
                                colors = CardDefaults.cardColors(
                                    containerColor = Color(0xFFE3F2FD)
                                ),
                                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                                shape = RoundedCornerShape(8.dp)
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(12.dp),
                                    horizontalArrangement = Arrangement.SpaceBetween,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    // 勾选框 - 使用更小的尺寸
                                    Checkbox(
                                        checked = combination.id in selectedCombinations,
                                        onCheckedChange = { checked ->
                                            selectedCombinations = if (checked) {
                                                selectedCombinations + combination.id
                                            } else {
                                                selectedCombinations - combination.id
                                            }
                                            // 同时更新区域选择状态
                                            val currentAreaSelections = areaSelectionStates[selectedArea] ?: emptySet()
                                            areaSelectionStates = areaSelectionStates.toMutableMap().apply {
                                                put(selectedArea, if (checked) {
                                                    currentAreaSelections + combination.id
                                                } else {
                                                    currentAreaSelections - combination.id
                                                })
                                            }
                                        },
                                        modifier = Modifier.size(20.dp)
                                    )
                                    
                                    Spacer(modifier = Modifier.width(6.dp))
                                    
                                    Column(modifier = Modifier.weight(1f)) {
                                        Text(
                                            text = "${combination.areaName}（厨师数量: ${combination.chefs.size}）",
                                            fontSize = 14.sp,
                                            fontWeight = FontWeight.Medium
                                        )
                                        Text(
                                            text = "保存时间: ${java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault()).format(java.util.Date(combination.savedTime))}",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                    
                                    // 只保留查看详情按钮
                                    OutlinedButton(
                                        onClick = { onSelectCombination(combination) },
                                        modifier = Modifier.height(25.dp),
                                        contentPadding = PaddingValues(horizontal = 6.dp, vertical = 0.dp)
                                    ) {
                                        Text("查看详情", fontSize = 9.sp)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 左侧：全选/取消全选、保存方案和删除按钮（左对齐）
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 全选/取消全选按钮（始终显示）
                    OutlinedButton(
                        onClick = {
                            if (filteredCombinations.isEmpty()) {
                                // 如果没有数据，点击无效果
                                return@OutlinedButton
                            }
                            val currentAreaSelections = areaSelectionStates[selectedArea] ?: emptySet()
                            if (currentAreaSelections.size == filteredCombinations.size) {
                                // 如果当前区域已全选，则取消全选
                                areaSelectionStates = areaSelectionStates.toMutableMap().apply {
                                    put(selectedArea, emptySet())
                                }
                                selectedCombinations = selectedCombinations - filteredCombinations.map { it.id }.toSet()
                            } else {
                                // 如果当前区域未全选，则全选
                                val newSelections = filteredCombinations.map { it.id }.toSet()
                                areaSelectionStates = areaSelectionStates.toMutableMap().apply {
                                    put(selectedArea, newSelections)
                                }
                                selectedCombinations = selectedCombinations + newSelections
                            }
                        },
                        enabled = filteredCombinations.isNotEmpty(), // 没有数据时禁用但仍显示
                        modifier = Modifier
                            .height(26.dp)
                            .width(70.dp), // 固定宽度，避免过大
                        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = MaterialTheme.colorScheme.primary,
                            disabledContentColor = MaterialTheme.colorScheme.primary,
                            containerColor = Color.Transparent
                        ),
                        border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary)
                    ) {
                        Text(
                            text = if (filteredCombinations.isNotEmpty() && (areaSelectionStates[selectedArea] ?: emptySet()).size == filteredCombinations.size) "取消全选" else "全选",
                            fontSize = 11.sp,
                            textAlign = TextAlign.Center
                        )
                    }
                    
                    // 保存方案按钮（始终显示）
                    OutlinedButton(
                        onClick = { 
                            if (selectedCombinations.isEmpty()) {
                                // 如果没有选择数据，显示提示
                                showCustomToast(context, "未选择任何组合")
                            } else {
                                showActionChoiceDialog = true
                            }
                        },
                        enabled = selectedCombinations.isNotEmpty(), // 没有选择时禁用但仍显示
                        modifier = Modifier
                            .height(26.dp)
                            .width(70.dp), // 固定宽度，避免过大
                        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = MaterialTheme.colorScheme.primary,
                            disabledContentColor = MaterialTheme.colorScheme.primary,
                            containerColor = Color.Transparent
                        ),
                        border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary)
                    ) {
                        Text("保存方案", fontSize = 11.sp, textAlign = TextAlign.Center)
                    }
                    
                    // 删除按钮（始终显示，减小宽度）
                    OutlinedButton(
                        onClick = { 
                            if (selectedCombinations.isEmpty()) {
                                // 如果没有选择数据，显示提示
                                showCustomToast(context, "未选择任何组合")
                            } else {
                                showBatchDeleteDialog = true
                            }
                        },
                        enabled = selectedCombinations.isNotEmpty(), // 没有选择时禁用但仍显示
                        modifier = Modifier
                            .height(26.dp)
                            .width(50.dp), // 减小宽度
                        contentPadding = PaddingValues(horizontal = 6.dp, vertical = 0.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = MaterialTheme.colorScheme.error,
                            disabledContentColor = MaterialTheme.colorScheme.error,
                            containerColor = Color.Transparent
                        ),
                        border = BorderStroke(1.dp, MaterialTheme.colorScheme.error)
                    ) {
                        Text("删除", fontSize = 11.sp, textAlign = TextAlign.Center)
                    }
                }
                
                // 右侧：关闭按钮
                TextButton(onClick = onDismiss) {
                    Text("关闭")
                }
            }
        }
    )
    
    // 操作选择弹窗
    if (showActionChoiceDialog) {
        ActionChoiceDialog(
            onNewScheme = {
                showActionChoiceDialog = false
                showSaveSchemeDialog = true
            },
            onAddToExisting = {
                showActionChoiceDialog = false
                showSchemesForMergeDialog = true
            },
            onDismiss = { showActionChoiceDialog = false }
        )
    }
    
    // 保存方案弹窗（仅新建）
    if (showSaveSchemeDialog) {
        SaveSchemeDialog(
            selectedCombinations = combinations.filter { it.id in selectedCombinations },
            schemeStorage = schemeStorage,
            onDismiss = { showSaveSchemeDialog = false },
            onSaved = { 
                selectedCombinations = emptySet()
                showSaveSchemeDialog = false
            }
        )
    }
    
    // 方案列表弹窗（查看/加载方案）
    if (showSchemesDialog) {
        SchemesListDialog(
            schemeStorage = schemeStorage,
            combinationStorage = combinationStorage,
            onDismiss = { showSchemesDialog = false },
            onLoadScheme = { scheme ->
                // 清空当前配置，加载方案配置
                combinationStorage.clearAllCombinations()
                scheme.combinations.forEach { combination ->
                    combinationStorage.saveCombination(combination)
                }
                showSchemesDialog = false
                // 如果有返回回调，调用它；否则完全关闭
                if (onReturnFromSchemeLoad != null) {
                    onReturnFromSchemeLoad()
                } else {
                    onDismiss()
                }
            }
        )
    }
    
    // 方案列表弹窗（合并模式）
    if (showSchemesForMergeDialog) {
        SchemesListDialog(
            schemeStorage = schemeStorage,
            combinationStorage = combinationStorage,
            onDismiss = { showSchemesForMergeDialog = false },
            onLoadScheme = { scheme ->
                // 这个不应该被调用，因为是合并模式
            },
            onSelectForMerge = { scheme ->
                // 选择方案进行合并
                val newCombinations = combinations.filter { it.id in selectedCombinations }
                val areaConflicts = schemeStorage.checkAreaConflicts(scheme, newCombinations)
                val chefConflicts = schemeStorage.checkChefConflicts(scheme, newCombinations)
                
                if (areaConflicts.isNotEmpty()) {
                    targetScheme = scheme
                    conflictAreas = areaConflicts
                    showAreaConflictDialog = true
                    showSchemesForMergeDialog = false
                } else if (chefConflicts.isNotEmpty()) {
                    targetScheme = scheme
                    conflictChefs = chefConflicts
                    showConflictDialog = true
                    showSchemesForMergeDialog = false
                } else {
                    // 没有冲突，直接合并
                    val updatedScheme = scheme.copy(
                        combinations = scheme.combinations + newCombinations,
                        createTime = System.currentTimeMillis()
                    )
                    schemeStorage.saveScheme(updatedScheme)
                    selectedCombinations = emptySet()
                    showSchemesForMergeDialog = false
                }
            },
            selectedCombinations = combinations.filter { it.id in selectedCombinations }
        )
    }
    
    // 地区冲突确认弹窗
    if (showAreaConflictDialog && targetScheme != null) {
        AreaConflictDialog(
            conflictAreas = conflictAreas,
            onConfirm = {
                // 覆盖保存：移除冲突地区的配置，添加新配置
                val newCombinations = combinations.filter { it.id in selectedCombinations }
                val filteredExistingCombinations = targetScheme!!.combinations.filter { existing ->
                    existing.areaName !in conflictAreas
                }
                val updatedScheme = targetScheme!!.copy(
                    combinations = filteredExistingCombinations + newCombinations,
                    createTime = System.currentTimeMillis()
                )
                schemeStorage.saveScheme(updatedScheme)
                selectedCombinations = emptySet()
                showAreaConflictDialog = false
                targetScheme = null
            },
            onDismiss = { 
                showAreaConflictDialog = false
                targetScheme = null
            }
        )
    }
    
    // 厨师冲突确认弹窗
    if (showConflictDialog && targetScheme != null) {
        ConflictConfirmDialog(
            conflictChefs = conflictChefs,
            onConfirm = {
                val updatedScheme = targetScheme!!.copy(
                    combinations = targetScheme!!.combinations + combinations.filter { it.id in selectedCombinations },
                    createTime = System.currentTimeMillis()
                )
                schemeStorage.saveScheme(updatedScheme)
                selectedCombinations = emptySet()
                showConflictDialog = false
                targetScheme = null
            },
            onDismiss = { 
                showConflictDialog = false
                targetScheme = null
            }
        )
    }
}

/**
 * 组合详情弹窗
 */
@Composable
private fun CombinationDetailsDialog(
    combination: SavedCombination,
    onDismiss: () -> Unit
) {
    Dialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true)
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.9f),
            colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)), // 与已保存配置弹窗相同的底色
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
            shape = RoundedCornerShape(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                // 计算总技法值（仅实验室区域）
                val isLabArea = combination.areaName in listOf("蒸", "炸", "炒", "煮", "切", "烤")
                val totalSkillValue = if (isLabArea) {
                    combination.chefs.sumOf { chef ->
                        // 从collectionDetails中提取技法值
                        val details = chef.collectionDetails
                        val skillValueRegex = Regex("技法值: (\\d+)")
                        val skillMatch = skillValueRegex.find(details)
                        val baseSkillValue = skillMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
                        
                        // 提取光环加成值
                        val auraRegex = Regex("= (\\d+)\\）")
                        val auraMatch = auraRegex.find(details)
                        val auraValue = auraMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
                        
                        baseSkillValue + auraValue
                    }
                } else 0
                
                // 标题栏，包含总技法值、标题和返回按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Column(
                        modifier = Modifier.weight(1f)
                    ) {
                        // 实验室区域显示总技法值
                        if (isLabArea) {
                            Text(
                                text = "${combination.areaName}：${totalSkillValue}-组合详情",
                                fontSize = 18.sp,
                                fontWeight = FontWeight.Bold
                            )
                        } else {
                    Text(
                        text = "${combination.areaName} - 组合详情",
                        fontSize = 18.sp,
                                fontWeight = FontWeight.Bold
                    )
                        }
                    }
                    
                    // 返回按钮
                    IconButton(
                        onClick = onDismiss
                    ) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = "返回",
                            tint = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
                
                Text(
                    text = "保存时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date(combination.savedTime))}",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 16.dp)
                )
                
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(1.dp) // 调整card间距为1dp
                ) {
                    items(combination.chefs) { chef ->
                        SavedChefRow(chef = chef)
                    }
                }
            }
        }
    }
}

/**
 * 保存的厨师信息行
 */
@Composable
private fun SavedChefRow(chef: SavedChefInfo) {
    // 判断地区类型
    val isLabArea = chef.area in listOf("蒸", "炸", "炒", "煮", "切", "烤")
    
    Box(
        modifier = Modifier
            .padding(4.dp) // 减小外边距
            .background(
                Color.White,
                RoundedCornerShape(8.dp)
            )
            .padding(8.dp) // 减小内边距
    ) {
        Column {
                        // 第一行：名称 + 星级 + 红色心法盘（实验室）或采集点详情（其他区域）
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = chef.name,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.width(6.dp))
                    // 星级显示
                    repeat(chef.rarity) {
                        Text(
                            text = "★",
                            fontSize = 12.sp,
                            color = Color(0xFF2196F3)
                        )
                    }
                    
                    // 实验室区域在星级后显示红色心法盘数量
                    if (isLabArea) {
                        Spacer(modifier = Modifier.width(6.dp))
                                                 Text(
                             text = if (chef.redAmberCount > 0) "红色心法盘X${chef.redAmberCount}" else "无红色心法盘",
                             fontSize = 10.sp,
                             color = if (chef.redAmberCount > 0) Color(0xFFF44336) else MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
                
                // 右侧显示：非实验室区域显示采集点详情
                if (!isLabArea) {
                Text(
                    text = buildAnnotatedString {
                        val details = chef.collectionDetails
                        
                        // 判断地区类型
                        val isJadeArea = chef.area in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
                        val isVegArea = chef.area in listOf("池塘", "牧场", "猪圈", "鸡舍", "作坊", "菜棚", "菜地", "森林")
                        
                        when {
                            isJadeArea -> {
                                // 玉片区高亮双类型采集点
                                val regex = Regex("(\\w+)\\+(\\w+):(\\d+)")
                                val match = regex.find(details)
                                if (match != null) {
                                    val type1 = match.groupValues[1]
                                    val type2 = match.groupValues[2]
                                    val value = match.groupValues[3]
                                    
                                    withStyle(style = SpanStyle(color = Color.Red)) {
                                        append("$type1+$type2:$value")
                                    }
                                } else {
                                    append(details)
                                }
                            }
                            isVegArea -> {
                                // 菜地区高亮对应采集类型
                                val targetType = when (chef.area) {
                                    "池塘" -> "鱼"
                                    "牧场", "猪圈", "鸡舍" -> "肉"
                                    "菜棚", "菜地", "森林" -> "菜"
                                    "作坊" -> "面"
                                    else -> ""
                                }
                                
                                val parts = details.split(" ")
                                parts.forEachIndexed { index, part ->
                                    if (index > 0) append(" ")
                                    
                                    val colonIndex = part.indexOf(":")
                                    if (colonIndex >= 0) {
                                        val type = part.substring(0, colonIndex)
                                        val value = part.substring(colonIndex)
                                        
                                        if (type == targetType) {
                                            withStyle(style = SpanStyle(color = Color.Red)) {
                                                append("$type$value")
                                            }
                                        } else {
                                            append("$type$value")
                                        }
                                    } else {
                                        append(part)
                                    }
                                }
                            }
                            else -> {
                                append(details)
                            }
                        }
                    },
                    fontSize = 11.sp
                )
            }
            }
            
                         if (isLabArea) {
                 // 实验室区域：第二行显示技法值和光环（同一行）
                 Spacer(modifier = Modifier.height(4.dp))
                 Text(
                     text = buildAnnotatedString {
                         val details = chef.collectionDetails
                         val auraStartIndex = details.indexOf("（光环：")
                         
                         if (auraStartIndex != -1) {
                             // 有光环信息，技法值红色，光环灰色
                             val skillPart = details.substring(0, auraStartIndex)
                             val auraPart = details.substring(auraStartIndex)
                             
                             withStyle(style = SpanStyle(color = Color(0xFFF44336), fontWeight = FontWeight.Bold)) {
                                 append(skillPart)
                             }
                             withStyle(style = SpanStyle(color = Color.Gray)) {
                                 append(auraPart)
                             }
                         } else {
                             // 没有光环信息，技法值红色显示
                             withStyle(style = SpanStyle(color = Color(0xFFF44336), fontWeight = FontWeight.Bold)) {
                                 append(details)
                             }
                         }
                     },
                     fontSize = 11.sp,
                     modifier = Modifier.fillMaxWidth()
                 )
            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 第三行：根据区域类型显示不同内容
            if (isLabArea) {
                // 实验室区域：第三行显示来源和修炼状态
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "来源: ${chef.origin.replace("<br>", "、")}",
                        fontSize = 11.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.weight(1f)
                    )
                    
                    if (chef.isUltimate) {
                        Text(
                            text = "已修炼",
                            fontSize = 10.sp,
                            color = Color(0xFF4CAF50),
                            modifier = Modifier
                                .background(
                                    Color(0xFF4CAF50).copy(alpha = 0.1f),
                                    RoundedCornerShape(4.dp)
                                )
                                .padding(horizontal = 6.dp, vertical = 2.dp)
                        )
                    }
                }
            } else {
                // 其他区域：第二行显示技能数据和修炼状态
                Spacer(modifier = Modifier.height(4.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                Row(
                        horizontalArrangement = Arrangement.spacedBy(6.dp)
                ) {
                    Text(
                        text = "素材:${chef.materialGain}%",
                        fontSize = 11.sp,
                        color = Color(0xFF2196F3)
                    )
                    Text(
                        text = "暴击素材:${chef.critMaterial}%",
                        fontSize = 11.sp,
                        color = Color(0xFF9C27B0)
                    )
                    Text(
                        text = "暴击率:${chef.critChance}%",
                        fontSize = 11.sp,
                        color = Color(0xFFFF5722)
                    )
                }
                
                if (chef.isUltimate) {
                    Text(
                        text = "已修炼",
                        fontSize = 10.sp,
                        color = Color(0xFF4CAF50),
                        modifier = Modifier
                            .background(
                                Color(0xFF4CAF50).copy(alpha = 0.1f),
                                RoundedCornerShape(4.dp)
                            )
                            .padding(horizontal = 6.dp, vertical = 2.dp)
                    )
                    }
                }
            }
        }
    }
}

/**
 * 显示无法满足采集点要求的地区提示对话框
 */
@Composable
private fun InsufficientAreasDialog(
    insufficientAreas: List<String>,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        confirmButton = {
            Button(
                onClick = onDismiss,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            ) {
                Text("确定")
            }
        },
        title = {
            Text(
                text = "采集点要求不满足",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Column {
                Text(
                    text = "以下地区无法满足采集点要求，请降低采集点要求重新查询：",
                    fontSize = 14.sp,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                
                insufficientAreas.forEach { area ->
                    Text(
                        text = "• $area",
                        fontSize = 13.sp,
                        color = Color(0xFFFF5722),
                        modifier = Modifier.padding(vertical = 2.dp)
                    )
                }
            }
        },
        containerColor = Color.White,
        titleContentColor = MaterialTheme.colorScheme.onSurface,
        textContentColor = MaterialTheme.colorScheme.onSurface
    )
}

/**
 * 选择厨师卡片组件
 */
@Composable
private fun SelectChefCard(
    areaName: String,
    onSelectChef: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .height(80.dp)
            .clickable { onSelectChef() },
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFFF5F5F5) // 浅灰色背景
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            contentAlignment = Alignment.Center
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = "添加厨师",
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.size(24.dp)
                )
                Text(
                    text = "选择厨师",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }
    }
}

/**
 * 保存方案弹窗
 */
@Composable
private fun SaveSchemeDialog(
    selectedCombinations: List<SavedCombination>,
    schemeStorage: SchemeStorage,
    onDismiss: () -> Unit,
    onSaved: () -> Unit
) {
    var schemeName by remember { mutableStateOf("") }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("保存方案", fontSize = 18.sp, fontWeight = FontWeight.Bold) },
        text = {
            Column {
                Text("已选择 ${selectedCombinations.size} 个配置", fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
                Spacer(modifier = Modifier.height(16.dp))
                
                OutlinedTextField(
                    value = schemeName,
                    onValueChange = { schemeName = it },
                    label = { Text("方案名称") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true
                )
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    if (schemeName.isNotBlank()) {
                        val newScheme = Scheme(
                            id = java.util.UUID.randomUUID().toString(),
                            name = schemeName,
                            combinations = selectedCombinations
                        )
                        schemeStorage.saveScheme(newScheme)
                        onSaved()
                    }
                },
                enabled = schemeName.isNotBlank()
            ) {
                Text("保存")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 方案列表弹窗
 */
@Composable
private fun SchemesListDialog(
    schemeStorage: SchemeStorage,
    combinationStorage: CombinationStorage,
    onDismiss: () -> Unit,
    onLoadScheme: (Scheme) -> Unit,
    onSelectForMerge: ((Scheme) -> Unit)? = null,
    selectedCombinations: List<SavedCombination>? = null
) {
    var schemes by remember { mutableStateOf<List<Scheme>>(emptyList()) }
    var showLoadConfirmDialog by remember { mutableStateOf(false) }
    var schemeToLoad by remember { mutableStateOf<Scheme?>(null) }
    var showDeleteConfirmDialog by remember { mutableStateOf(false) }
    var schemeToDelete by remember { mutableStateOf<Scheme?>(null) }
    var showSchemeDetailsDialog by remember { mutableStateOf(false) }
    var schemeToView by remember { mutableStateOf<Scheme?>(null) }
    var showImportDialog by remember { mutableStateOf(false) }
    var showExportDialog by remember { mutableStateOf<Scheme?>(null) }
    
    // 用于收集所有待保存的方案名称修改
    var pendingNameChanges by remember { mutableStateOf<Map<String, String>>(emptyMap()) }
    
    // 监听用户切换，当用户切换时刷新方案列表
    val context = LocalContext.current
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId()) }
    
    LaunchedEffect(Unit) {
        schemes = schemeStorage.getAllSchemes()
    }
    
    // 监听用户ID变化
    LaunchedEffect(Unit) {
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId()
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 用户切换了，刷新方案列表
                schemes = schemeStorage.getAllSchemes()
            }
            delay(500) // 每500毫秒检查一次
        }
    }
    
    val focusManager = LocalFocusManager.current
    
    // 辅助函数：清除焦点并保存所有待保存的修改
    fun clearFocusAndSave() {
        pendingNameChanges.forEach { (schemeId, newName) ->
            val originalScheme = schemes.find { it.id == schemeId }
            if (originalScheme != null && newName.isNotBlank() && newName != originalScheme.name) {
                schemeStorage.updateSchemeName(schemeId, newName)
            }
        }
        focusManager.clearFocus()
        schemes = schemeStorage.getAllSchemes()
        pendingNameChanges = emptyMap()
    }
    
    AlertDialog(
        onDismissRequest = {
            clearFocusAndSave()
            onDismiss()
        },
        title = { 
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = if (onSelectForMerge != null) "选择要加入的方案" else "保存的方案", 
                    fontSize = 18.sp, 
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f)
                )
                
                // 导入按钮（仅在查看模式下显示）
                if (onSelectForMerge == null) {
                    OutlinedButton(
                        onClick = { showImportDialog = true },
                        modifier = Modifier.height(28.dp),
                        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = MaterialTheme.colorScheme.primary
                        ),
                        border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary)
                    ) {
                        Text("导入", fontSize = 10.sp)
                    }
                }
            }
        },
        text = {
            // 容器，用于清除焦点并保存
            Box(
                modifier = Modifier
                    .fillMaxWidth()
            ) {
            if (schemes.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text("暂无保存的方案", color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            } else {
                LazyColumn(
                    modifier = Modifier.heightIn(max = 280.dp)
                ) {
                    items(schemes) { scheme ->
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp),
                            colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD))
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(12.dp),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                // 左侧：方案信息
                                Column(
                                    modifier = Modifier
                                        .weight(1f)
                                        .padding(end = 8.dp)
                                ) {
                                    // 方案名称（根据模式显示不同内容）
                                    if (onSelectForMerge != null) {
                                        // 加入模式：显示不可编辑的文本
                                        Text(
                                            text = scheme.name,
                                            fontSize = 14.sp,
                                            fontWeight = FontWeight.Medium,
                                            color = MaterialTheme.colorScheme.onSurface
                                        )
                                    } else {
                                        // 查看模式：显示可编辑的输入框
                                        SmallTextField(
                                            value = pendingNameChanges[scheme.id] ?: scheme.name,
                                            onValueChange = { newName ->
                                                // 收集待保存的修改
                                                pendingNameChanges = pendingNameChanges.toMutableMap().apply {
                                                    if (newName != scheme.name) {
                                                        put(scheme.id, newName)
                                                    } else {
                                                        remove(scheme.id)
                                                    }
                                                }
                                            },
                                            onValueCommit = { newName ->
                                                if (newName.isNotBlank() && newName != scheme.name) {
                                                    schemeStorage.updateSchemeName(scheme.id, newName)
                                                    schemes = schemeStorage.getAllSchemes()
                                                    // 清除已保存的待保存状态
                                                    pendingNameChanges = pendingNameChanges.toMutableMap().apply {
                                                        remove(scheme.id)
                                                    }
                                                }
                                            },
                                            widthDp = 110.dp
                                        )
                                    }
                                    // 第二行：配置数量
                                    Text(
                                        "${scheme.combinations.size} 个配置",
                                        fontSize = 12.sp,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                                
                                // 右侧：操作按钮
                                Column(
                                    verticalArrangement = Arrangement.spacedBy(4.dp),
                                    horizontalAlignment = Alignment.End
                                ) {
                                    if (onSelectForMerge != null) {
                                        // 加入模式：显示加入按钮
                                        Button(
                                            onClick = { 
                                                clearFocusAndSave()
                                                onSelectForMerge(scheme)
                                            },
                                            modifier = Modifier.height(28.dp),
                                            contentPadding = PaddingValues(horizontal = 12.dp, vertical = 0.dp),
                                            colors = ButtonDefaults.buttonColors(
                                                containerColor = MaterialTheme.colorScheme.primary
                                            )
                                        ) {
                                            Text("加入", fontSize = 10.sp, color = MaterialTheme.colorScheme.onPrimary)
                                        }
                                    } else {
                                        // 查看模式：第一行显示加载和查看详情按钮
                                        Row(
                                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                                        ) {
                                            OutlinedButton(
                                                onClick = { 
                                                    clearFocusAndSave()
                                                    schemeToLoad = scheme
                                                    showLoadConfirmDialog = true
                                                },
                                                modifier = Modifier.height(25.dp),
                                                contentPadding = PaddingValues(horizontal = 6.dp, vertical = 0.dp),
                                                colors = ButtonDefaults.outlinedButtonColors(
                                                    contentColor = MaterialTheme.colorScheme.primary
                                                ),
                                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary)
                                            ) {
                                                Text("加载", fontSize = 9.sp)
                                            }
                                            
                                            OutlinedButton(
                                                onClick = { 
                                                    clearFocusAndSave()
                                                    schemeToView = scheme
                                                    showSchemeDetailsDialog = true
                                                },
                                                modifier = Modifier.height(25.dp),
                                                contentPadding = PaddingValues(horizontal = 6.dp, vertical = 0.dp)
                                            ) {
                                                Text("查看详情", fontSize = 9.sp)
                                            }
                                        }
                                        
                                        // 第二行显示导出和删除按钮
                                        Row(
                                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                                        ) {
                                            // 导出按钮
                                            OutlinedButton(
                                                onClick = { 
                                                    clearFocusAndSave()
                                                    showExportDialog = scheme
                                                },
                                                modifier = Modifier.height(25.dp),
                                                contentPadding = PaddingValues(horizontal = 6.dp, vertical = 0.dp),
                                                colors = ButtonDefaults.outlinedButtonColors(
                                                    contentColor = Color(0xFF4CAF50) // 绿色
                                                ),
                                                border = BorderStroke(1.dp, Color(0xFF4CAF50))
                                            ) {
                                                Text("导出", fontSize = 9.sp)
                                            }
                                            
                                            // 删除按钮
                                            OutlinedButton(
                                                onClick = { 
                                                    clearFocusAndSave()
                                                    schemeToDelete = scheme
                                                    showDeleteConfirmDialog = true
                                                },
                                                modifier = Modifier.height(25.dp),
                                                contentPadding = PaddingValues(horizontal = 6.dp, vertical = 0.dp),
                                                colors = ButtonDefaults.outlinedButtonColors(
                                                    contentColor = MaterialTheme.colorScheme.error
                                                ),
                                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.error)
                                            ) {
                                                Text("删除", fontSize = 9.sp)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            }
        },
        confirmButton = {
            TextButton(onClick = {
                clearFocusAndSave()
                onDismiss()
            }) {
                Text("关闭")
            }
        }
    )
    
    // 加载确认弹窗
    if (showLoadConfirmDialog && schemeToLoad != null) {
        AlertDialog(
            onDismissRequest = { showLoadConfirmDialog = false },
            title = { Text("确认加载") },
            text = { Text("加载方案「${schemeToLoad!!.name}」将清空当前所有组合配置，确定要继续吗？") },
            confirmButton = {
                Button(
                    onClick = {
                        onLoadScheme(schemeToLoad!!)
                        showLoadConfirmDialog = false
                    }
                ) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(onClick = { showLoadConfirmDialog = false }) {
                    Text("取消")
                }
            }
        )
    }
    
    // 删除方案确认弹窗
    if (showDeleteConfirmDialog && schemeToDelete != null) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirmDialog = false },
            title = { Text("确认删除") },
            text = { Text("确定要删除方案「${schemeToDelete!!.name}」吗？此操作不可撤销。") },
            confirmButton = {
                Button(
                    onClick = {
                        schemeStorage.deleteScheme(schemeToDelete!!.id)
                        schemes = schemeStorage.getAllSchemes()
                        showDeleteConfirmDialog = false
                        schemeToDelete = null
                    },
                    colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)
                ) {
                    Text("确认删除")
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirmDialog = false }) {
                    Text("取消")
                }
            }
        )
    }
    
    // 方案详情弹窗
    if (showSchemeDetailsDialog && schemeToView != null) {
        SchemeDetailsDialog(
            scheme = schemeToView!!,
            onDismiss = { 
                showSchemeDetailsDialog = false
                schemeToView = null
            }
        )
    }
    
    // 导入弹窗
    if (showImportDialog) {
        ImportSchemeDialog(
            onDismiss = { showImportDialog = false },
            onImport = { importedScheme ->
                // 导入成功后刷新方案列表
                schemes = schemeStorage.getAllSchemes()
                showImportDialog = false
                // 显示导入成功提示
                showCustomToast(context, "方案导入成功")
            }
        )
    }
    
    // 导出弹窗
    if (showExportDialog != null) {
        ExportSchemeDialog(
            scheme = showExportDialog!!,
            onDismiss = { showExportDialog = null },
            onExport = { fileName ->
                exportSchemeToJson(context, showExportDialog!!, fileName)
                showExportDialog = null
            }
        )
    }
}

/**
 * 操作选择弹窗
 */
@Composable
private fun ActionChoiceDialog(
    onNewScheme: () -> Unit,
    onAddToExisting: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("选择操作", fontSize = 18.sp, fontWeight = FontWeight.Bold) },
        text = {
            Column {
                Text("请选择要执行的操作：", fontSize = 14.sp)
                Spacer(modifier = Modifier.height(16.dp))
                
                // 新建方案按钮
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onNewScheme() },
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD))
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Add,
                            contentDescription = "新建方案",
                            tint = MaterialTheme.colorScheme.primary
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Column {
                            Text("新建方案", fontWeight = FontWeight.Medium)
                            Text("创建一个新的方案", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 加入现有方案按钮
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onAddToExisting() },
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD))
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.KeyboardArrowUp,
                            contentDescription = "加入现有方案",
                            tint = MaterialTheme.colorScheme.primary
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Column {
                            Text("加入现有方案", fontWeight = FontWeight.Medium)
                            Text("将配置合并到已有方案中", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
                        }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 地区冲突确认弹窗
 */
@Composable
private fun AreaConflictDialog(
    conflictAreas: List<String>,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("地区配置冲突", fontSize = 18.sp, fontWeight = FontWeight.Bold) },
        text = {
            Column {
                Text("以下地区在目标方案中已有配置：")
                Spacer(modifier = Modifier.height(8.dp))
                LazyColumn(
                    modifier = Modifier.heightIn(max = 150.dp)
                ) {
                    items(conflictAreas) { areaName ->
                        Text(
                            "• $areaName",
                            fontSize = 14.sp,
                            modifier = Modifier.padding(vertical = 2.dp)
                        )
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
                Text("是否要覆盖现有配置？", fontSize = 14.sp, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.error)
            }
        },
        confirmButton = {
            Button(
                onClick = onConfirm,
                colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)
            ) {
                Text("覆盖")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 冲突确认弹窗
 */
@Composable
private fun ConflictConfirmDialog(
    conflictChefs: List<String>,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("厨师冲突", fontSize = 18.sp, fontWeight = FontWeight.Bold) },
        text = {
            Column {
                Text("以下厨师在目标方案中已存在：")
                Spacer(modifier = Modifier.height(8.dp))
                LazyColumn(
                    modifier = Modifier.heightIn(max = 150.dp)
                ) {
                    items(conflictChefs) { chefName ->
                        Text(
                            "• $chefName",
                            fontSize = 14.sp,
                            modifier = Modifier.padding(vertical = 2.dp)
                        )
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
                Text("是否仍要添加到该方案中？", fontSize = 14.sp)
            }
        },
        confirmButton = {
            Button(onClick = onConfirm) {
                Text("仍要添加")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}


/**
 * 方案详情弹窗
 */
@Composable
private fun SchemeDetailsDialog(
    scheme: Scheme,
    onDismiss: () -> Unit
) {
    // 定义每个区域包含的地点
    val getAreaType = { areaName: String ->
        when {
            areaName in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫") -> "玉片区"
            areaName in listOf("池塘", "牧场", "猪圈", "鸡舍", "作坊", "菜棚", "菜地", "森林") -> "菜地区"
            areaName in listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁") -> "调料区"
            areaName in listOf("蒸", "炸", "炒", "煮", "切", "烤") -> "实验室"
            else -> "调料区" // 默认归类到调料区
        }
    }
    
    // 四个区域
    val safeAreas = listOf("玉片区", "菜地区", "调料区", "实验室")
    
    // 默认选择菜地区（索引为1）
    var selectedTabIndex by remember { mutableStateOf(1) }
    
    // 按当前选中的标签过滤组合
    val selectedArea = if (selectedTabIndex < safeAreas.size) safeAreas[selectedTabIndex] else safeAreas.lastOrNull() ?: "调料区"
    val filteredCombinations = scheme.combinations.filter { getAreaType(it.areaName) == selectedArea }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { 
            Text("方案详情 - ${scheme.name}", fontSize = 18.sp, fontWeight = FontWeight.Bold)
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 500.dp)
            ) {
                // 方案信息
                Text(
                    text = "共 ${scheme.combinations.size} 个配置",
                    fontSize = 14.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 12.dp)
                )
                
                // 三段切换标签
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    shape = RoundedCornerShape(20.dp),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Row(modifier = Modifier.padding(4.dp)) {
                        safeAreas.forEachIndexed { index, area ->
                            val selected = selectedTabIndex == index
                            Surface(
                                onClick = { selectedTabIndex = index },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(28.dp),
                                shape = RoundedCornerShape(16.dp),
                                color = if (selected) MaterialTheme.colorScheme.primary else Color.Transparent
                            ) {
                                Box(
                                    modifier = Modifier.fillMaxSize(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = area,
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium,
                                        color = if (selected) Color.White else MaterialTheme.colorScheme.primary
                                    )
                                }
                            }
                            if (index < safeAreas.lastIndex) Spacer(modifier = Modifier.width(4.dp))
                        }
                    }
                }
                
                // 配置列表
                if (filteredCombinations.isEmpty()) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text("该区域暂无配置", color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                } else {
                    LazyColumn(
                        modifier = Modifier.fillMaxWidth(),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        items(filteredCombinations) { combination ->
                            Card(
                                modifier = Modifier.fillMaxWidth(),
                                colors = CardDefaults.cardColors(
                                    containerColor = Color(0xFFF8F9FA)
                                ),
                                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
                                shape = RoundedCornerShape(8.dp)
                            ) {
                                Column(
                                    modifier = Modifier.padding(12.dp)
                                ) {
                                    // 第一行：地区名 + 厨师数量
                                    Text(
                                        text = "${combination.areaName}  ${combination.chefs.size} 个厨师：",
                                        fontSize = 14.sp,
                                        fontWeight = FontWeight.Medium,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                    Spacer(modifier = Modifier.height(4.dp))
                                    // 第二行：只显示厨师名字
                                    Text(
                                        text = combination.chefs.joinToString("、") { it.name },
                                        fontSize = 12.sp,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("关闭")
            }
        }
    )
}

/**
 * 判断是否为玉片区
 */
private fun isJadeArea(areaName: String): Boolean {
    return areaName in listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
}

/**
 * 计算双采集点的理论最大值
 */
private fun calculateDualCollectionTheoreticalMax(chef: ChefResultWithSkills, theoreticalMaxValues: TheoreticalMaxValues): String {
    val dualTypes = when (chef.chefArea) {
        "藏心亭" -> "肉+菜"
        "朝阴山" -> "肉+面"
        "北冥城" -> "鱼+面"
        "清空谷" -> "肉+鱼"
        "还寒洞" -> "菜+面"
        "永昼宫" -> "菜+鱼"
        else -> return ""
    }
    
    // 计算双类型的理论最大值总和
    val totalValue = when (chef.chefArea) {
        "藏心亭" -> theoreticalMaxValues.meat + theoreticalMaxValues.veg
        "朝阴山" -> theoreticalMaxValues.meat + theoreticalMaxValues.creation
        "北冥城" -> theoreticalMaxValues.fish + theoreticalMaxValues.creation
        "清空谷" -> theoreticalMaxValues.meat + theoreticalMaxValues.fish
        "还寒洞" -> theoreticalMaxValues.veg + theoreticalMaxValues.creation
        "永昼宫" -> theoreticalMaxValues.veg + theoreticalMaxValues.fish
        else -> 0
    }
    
    return "$dualTypes：$totalValue"
}

/**
 * 重新计算玉片区全场加成（替换厨师后）- JADE AREA UPDATE
 * @param currentResults 当前查询结果
 * @param areaName 地区名称
 * @param oldChefName 被替换的厨师名称
 * @param newChef 新厨师
 * @param gameData 游戏数据
 * @return 重新计算后的查询结果
 */
private fun recalculateJadeAreaWithGlobalBonus(
    currentResults: List<ChefResult>,
    areaName: String,
    oldChefName: String,
    newChef: ChefResult,
    gameData: GameData,
    personalData: PersonalData?,
    useAllUltimateTraining: Boolean
): List<ChefResult> {
    val updatedResults = currentResults.toMutableList()
    
    // 获取被替换的厨师和新厨师的全场加成信息
    val oldChef = gameData.chefs.find { it.name == oldChefName }
    val newChefData = gameData.chefs.find { it.name == newChef.name }
    
    if (oldChef == null || newChefData == null) return currentResults
    
    val oldGlobalBonus = CollectionTeamCalculator.calculateGlobalBonusValues(oldChef, gameData, personalData, useAllUltimateTraining)
    val newGlobalBonus = CollectionTeamCalculator.calculateGlobalBonusValues(newChefData, gameData, personalData, useAllUltimateTraining)
    
    // 计算全场加成的差值
    val meatDiff = newGlobalBonus.meatBonus - oldGlobalBonus.meatBonus
    val fishDiff = newGlobalBonus.fishBonus - oldGlobalBonus.fishBonus
    val vegDiff = newGlobalBonus.vegBonus - oldGlobalBonus.vegBonus
    val creationDiff = newGlobalBonus.creationBonus - oldGlobalBonus.creationBonus
    
    // 注意：即使全场加成没有变化，新替换的厨师仍然需要享受场上其他厨师的全场加成效果
    // 所以这里不能直接返回，需要继续处理
    
    // 更新该地区所有厨师的采集点数值（包括新替换的厨师）
    updatedResults.forEach { result ->
        if (result.area == areaName && result is ChefResultWithSkills) {
            var updatedResult = result
            
            // 如果是新替换的厨师，需要计算场上其他厨师的全场加成效果
            if (result.name == newChef.name) {
                // 计算场上其他厨师对新替换厨师的全场加成
                val otherChefsGlobalBonus = calculateOtherChefsGlobalBonus(
                    updatedResults, areaName, newChef.name, gameData, personalData, useAllUltimateTraining
                )
                
                // 应用其他厨师的全场加成到新替换厨师
                updatedResult = result.copy(
                    totalMeat = result.totalMeat + otherChefsGlobalBonus.meatBonus,
                    totalFish = result.totalFish + otherChefsGlobalBonus.fishBonus,
                    totalVeg = result.totalVeg + otherChefsGlobalBonus.vegBonus,
                    totalCreation = result.totalCreation + otherChefsGlobalBonus.creationBonus
                )
            } else {
                // 其他厨师，根据全场加成差值调整采集点数值
                updatedResult = result.copy(
                    totalMeat = result.totalMeat + meatDiff,
                    totalFish = result.totalFish + fishDiff,
                    totalVeg = result.totalVeg + vegDiff,
                    totalCreation = result.totalCreation + creationDiff
                )
            }
            
            // 根据地区类型确定需要调整的采集点类型
            val (type1, type2) = when (areaName) {
                "藏心亭" -> "肉" to "菜"
                "朝阴山" -> "肉" to "面"
                "北冥城" -> "鱼" to "面"
                "清空谷" -> "肉" to "鱼"
                "还寒洞" -> "菜" to "面"
                "永昼宫" -> "菜" to "鱼"
                else -> "" to ""
            }
            
            // 计算双类型采集点总和（根据地区类型）
            val dualTypeTotal = when (areaName) {
                "藏心亭" -> updatedResult.totalMeat + updatedResult.totalVeg
                "朝阴山" -> updatedResult.totalMeat + updatedResult.totalCreation
                "北冥城" -> updatedResult.totalFish + updatedResult.totalCreation
                "清空谷" -> updatedResult.totalMeat + updatedResult.totalFish
                "还寒洞" -> updatedResult.totalVeg + updatedResult.totalCreation
                "永昼宫" -> updatedResult.totalVeg + updatedResult.totalFish
                else -> 0
            }
            
            // 构建双类型采集点描述
            val dualTypeDescription = when (areaName) {
                "藏心亭" -> "肉+菜:$dualTypeTotal"
                "朝阴山" -> "肉+面:$dualTypeTotal"
                "北冥城" -> "鱼+面:$dualTypeTotal"
                "清空谷" -> "肉+鱼:$dualTypeTotal"
                "还寒洞" -> "菜+面:$dualTypeTotal"
                "永昼宫" -> "菜+鱼:$dualTypeTotal"
                else -> ""
            }
            
            // 更新采集点详情字符串，使用双类型描述
            val finalResult = updatedResult.copy(
                chefCollectionDetails = dualTypeDescription
            )
            
            // 替换原结果
            val index = updatedResults.indexOf(result)
            if (index != -1) {
                updatedResults[index] = finalResult
            }
        }
    }
    
    return updatedResults
}

/**
 * 计算场上其他厨师对新替换厨师的全场加成
 * @param currentResults 当前查询结果
 * @param areaName 地区名称
 * @param newChefName 新替换的厨师名称
 * @param gameData 游戏数据
 * @return 全场加成信息
 */
private fun calculateOtherChefsGlobalBonus(
    currentResults: List<ChefResult>,
    areaName: String,
    newChefName: String,
    gameData: GameData,
    personalData: PersonalData?,
    useAllUltimateTraining: Boolean
): CollectionTeamCalculator.GlobalBonusInfo {
    val totalBonus = CollectionTeamCalculator.GlobalBonusInfo()
    
    // 遍历该地区的所有厨师（除了新替换的厨师）
    currentResults.forEach { result ->
        if (result.area == areaName && result.name != newChefName && result is ChefResultWithSkills) {
            // 找到该厨师的数据
            val chef = gameData.chefs.find { it.name == result.name }
            if (chef != null) {
                // 计算该厨师的全场加成
                val chefGlobalBonus = CollectionTeamCalculator.calculateGlobalBonusValues(chef, gameData, personalData, useAllUltimateTraining)
                
                // 累加全场加成
                totalBonus.meatBonus += chefGlobalBonus.meatBonus
                totalBonus.fishBonus += chefGlobalBonus.fishBonus
                totalBonus.vegBonus += chefGlobalBonus.vegBonus
                totalBonus.creationBonus += chefGlobalBonus.creationBonus
            }
        }
    }
    
    return totalBonus
}

/**
 * 重新计算菜地区全场加成（替换厨师后）- VEG AREA UPDATE
 * @param currentResults 当前查询结果
 * @param areaName 地区名称
 * @param oldChefName 被替换的厨师名称
 * @param newChef 新厨师
 * @param gameData 游戏数据
 * @return 重新计算后的查询结果
 */
private fun recalculateVegAreaWithGlobalBonus(
    currentResults: List<ChefResult>,
    areaName: String,
    oldChefName: String,
    newChef: ChefResult,
    gameData: GameData,
    personalData: PersonalData?,
    useAllUltimateTraining: Boolean
): List<ChefResult> {
    val updatedResults = currentResults.toMutableList()
    
    // 获取被替换的厨师和新厨师的全场加成信息
    val oldChef = gameData.chefs.find { it.name == oldChefName }
    val newChefData = gameData.chefs.find { it.name == newChef.name }
    
    if (oldChef == null || newChefData == null) return currentResults
    
    val oldGlobalBonus = CollectionTeamCalculator.calculateGlobalBonusValues(oldChef, gameData, personalData, useAllUltimateTraining)
    val newGlobalBonus = CollectionTeamCalculator.calculateGlobalBonusValues(newChefData, gameData, personalData, useAllUltimateTraining)
    
    // 计算全场加成的差值
    val meatDiff = newGlobalBonus.meatBonus - oldGlobalBonus.meatBonus
    val fishDiff = newGlobalBonus.fishBonus - oldGlobalBonus.fishBonus
    val vegDiff = newGlobalBonus.vegBonus - oldGlobalBonus.vegBonus
    val creationDiff = newGlobalBonus.creationBonus - oldGlobalBonus.creationBonus
    
    // 注意：即使全场加成没有变化，新替换的厨师仍然需要享受场上其他厨师的全场加成效果
    // 所以这里不能直接返回，需要继续处理
    
    // 更新该地区所有厨师的采集点数值（包括新替换的厨师）
    updatedResults.forEach { result ->
        if (result.area == areaName && result is ChefResultWithSkills) {
            var updatedResult = result
            
            // 如果是新替换的厨师，需要计算场上其他厨师的全场加成效果
            if (result.name == newChef.name) {
                // 计算场上其他厨师对新替换厨师的全场加成
                val otherChefsGlobalBonus = calculateOtherChefsGlobalBonus(
                    updatedResults, areaName, newChef.name, gameData, personalData, useAllUltimateTraining
                )
                
                // 应用其他厨师的全场加成到新替换厨师
                updatedResult = result.copy(
                    totalMeat = result.totalMeat + otherChefsGlobalBonus.meatBonus,
                    totalFish = result.totalFish + otherChefsGlobalBonus.fishBonus,
                    totalVeg = result.totalVeg + otherChefsGlobalBonus.vegBonus,
                    totalCreation = result.totalCreation + otherChefsGlobalBonus.creationBonus
                )
            } else {
                // 其他厨师，根据全场加成差值调整采集点数值
                updatedResult = result.copy(
                    totalMeat = result.totalMeat + meatDiff,
                    totalFish = result.totalFish + fishDiff,
                    totalVeg = result.totalVeg + vegDiff,
                    totalCreation = result.totalCreation + creationDiff
                )
            }
            
            // 构建采集点详情字符串（菜地区显示四种类型）
            val collectionDetails = "肉:${updatedResult.totalMeat} 鱼:${updatedResult.totalFish} 菜:${updatedResult.totalVeg} 面:${updatedResult.totalCreation}"
            
            // 更新采集点详情字符串
            val finalResult = updatedResult.copy(
                chefCollectionDetails = collectionDetails
            )
            
            // 替换原结果
            val index = updatedResults.indexOf(result)
            if (index != -1) {
                updatedResults[index] = finalResult
            }
        }
    }
    
    return updatedResults
}

/**
 * 更新新替换厨师的显示格式为双类型采集点总和
 * @param currentResults 当前查询结果
 * @param areaName 地区名称
 * @param newChef 新厨师
 * @param gameData 游戏数据
 * @return 更新后的查询结果
 */
private fun updateNewChefDisplayFormat(
    currentResults: List<ChefResult>,
    areaName: String,
    newChef: ChefResult,
    gameData: GameData
): List<ChefResult> {
    val updatedResults = currentResults.toMutableList()
    
    // 找到新替换的厨师
    val newChefResult = updatedResults.find { it.name == newChef.name && it.area == areaName }
    if (newChefResult is ChefResultWithSkills) {
        // 计算双类型采集点总和（根据地区类型）
        val dualTypeTotal = when (areaName) {
            "藏心亭" -> newChefResult.totalMeat + newChefResult.totalVeg
            "朝阴山" -> newChefResult.totalMeat + newChefResult.totalCreation
            "北冥城" -> newChefResult.totalFish + newChefResult.totalCreation
            "清空谷" -> newChefResult.totalMeat + newChefResult.totalFish
            "还寒洞" -> newChefResult.totalVeg + newChefResult.totalCreation
            "永昼宫" -> newChefResult.totalVeg + newChefResult.totalFish
            else -> 0
        }
        
        // 构建双类型采集点描述
        val dualTypeDescription = when (areaName) {
            "藏心亭" -> "肉+菜:$dualTypeTotal"
            "朝阴山" -> "肉+面:$dualTypeTotal"
            "北冥城" -> "鱼+面:$dualTypeTotal"
            "清空谷" -> "肉+鱼:$dualTypeTotal"
            "还寒洞" -> "菜+面:$dualTypeTotal"
            "永昼宫" -> "菜+鱼:$dualTypeTotal"
            else -> ""
        }
        
        // 更新新厨师的采集点详情显示
        val updatedNewChef = newChefResult.copy(
            chefCollectionDetails = dualTypeDescription
        )
        
        // 替换原结果
        val index = updatedResults.indexOf(newChefResult)
        if (index != -1) {
            updatedResults[index] = updatedNewChef
        }
    }
    
    return updatedResults
}

/**
 * 综合查询使用说明弹窗组件
 */
@Composable
private fun ComprehensiveQueryUsageDialog(
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "查询采集编队使用说明",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            LazyColumn(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                item {
                    Text(
                        text = "功能概述",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "采集编队查询功能可自动查询最优厨师编队分配方案，提高采集效率。",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }

                item {
                    Text(
                        text = "配置、查询功能",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "• 配置区域中开关按钮控制该区域是否参与查询，拖动可调整查询优先级\n• 配置页面中，可设置上场人数及采集点档位，拖动可调整查询优先级\n• 配置完成之后会，点击一键查询，系统会根据厨师的技能、厨具、心法盘等自动计算最佳采集方案\n• 查询结果可使用替换功能进行手动调整，替换的厨师会从已分配地区中移除",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }
                
                item {
                    Text(
                        text = "保存组合、方案功能",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "• 查询结果中可保存组合，可保存当前地区的厨师组合，在后续查询中不会使用已保存的厨师\n• 编队配置中选择已保存的组合可以保存为方案，点击对应方案可加载为当前组合配置\n• 导出配置后，配置保存在手机下载文件夹中，并且可导入方案数据，现不支持导入其他玩家方案",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("知道了")
            }
        }
    )
}

/**
 * 导出方案到JSON文件（直接复制到下载文件夹）
 */
private fun exportSchemeToJson(context: android.content.Context, scheme: Scheme, customFileName: String) {
    try {
        // 使用Gson创建JSON数据
        val gson = com.google.gson.Gson()
        val jsonData = gson.toJson(scheme)
        
        // 确保文件名以.json结尾
        val fileName = if (customFileName.endsWith(".json")) customFileName else "$customFileName.json"
        
        // 获取下载文件夹路径
        val downloadsDir = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS)
        val targetFile = java.io.File(downloadsDir, fileName)
        
        // 直接写入下载文件夹
        targetFile.writeText(jsonData, java.nio.charset.StandardCharsets.UTF_8)
        
        // 显示成功提示
        showCustomToast(context, "方案已导出到下载文件夹")
        
    } catch (e: Exception) {
        // 显示错误提示
        showCustomToast(context, "导出失败：${e.message}")
    }
}

/**
 * 导出弹窗组件
 */
@Composable
private fun ExportSchemeDialog(
    scheme: Scheme,
    onDismiss: () -> Unit,
    onExport: (String) -> Unit
) {
    var fileName by remember { mutableStateOf("${scheme.name}_方案") }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("导出方案", fontSize = 18.sp, fontWeight = FontWeight.Bold) },
        text = {
            Column(
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = "请输入导出文件名：",
                    fontSize = 14.sp
                )
                
                // 文件名输入框
                OutlinedTextField(
                    value = fileName,
                    onValueChange = { fileName = it },
                    label = { Text("文件名") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    placeholder = { Text("请输入文件名（无需输入.json后缀）") }
                )
                
                // 导出说明
                Text(
                    text = "文件将保存到下载文件夹中",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        },
        confirmButton = {
            Button(
                onClick = { onExport(fileName) },
                enabled = fileName.isNotBlank()
            ) {
                Text("导出")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 导入弹窗组件
 */
@Composable
private fun ImportSchemeDialog(
    onDismiss: () -> Unit,
    onImport: (Scheme) -> Unit
) {
    var selectedFile by remember { mutableStateOf<android.net.Uri?>(null) }
    var fileName by remember { mutableStateOf("") }
    
    val context = LocalContext.current
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let {
            selectedFile = it
            fileName = getFileNameFromUri(context, it) ?: "未知文件"
        }
    }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("导入方案", fontSize = 18.sp, fontWeight = FontWeight.Bold) },
        text = {
            Column(
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = "请选择要导入的方案JSON文件：",
                    fontSize = 14.sp
                )
                
                // 文件选择按钮
                OutlinedButton(
                    onClick = { launcher.launch("application/json") },
                    modifier = Modifier.fillMaxWidth(),
                    colors = ButtonDefaults.outlinedButtonColors(
                        contentColor = MaterialTheme.colorScheme.primary
                    ),
                    border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary)
                ) {
                    Text("选择文件")
                }
                
                // 显示选中的文件名
                if (fileName.isNotEmpty()) {
                    Text(
                        text = "已选择：$fileName",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                // 导入说明
                Text(
                    text = "注意：导入的方案将覆盖同名方案",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.error
                )
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    selectedFile?.let { uri ->
                        importSchemeFromJson(context, uri, onImport)
                    }
                },
                enabled = selectedFile != null
            ) {
                Text("导入")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 从JSON文件导入方案
 */
private fun importSchemeFromJson(context: android.content.Context, uri: android.net.Uri, onImport: (Scheme) -> Unit) {
    try {
        // 读取文件内容
        val inputStream = context.contentResolver.openInputStream(uri)
        val jsonString = inputStream?.bufferedReader().use { it?.readText() } ?: ""
        inputStream?.close()
        
        if (jsonString.isBlank()) {
            showCustomToast(context, "文件内容为空")
            return
        }
        
        // 解析JSON
        val gson = com.google.gson.Gson()
        val scheme = gson.fromJson(jsonString, com.example.show_auto.data.Scheme::class.java)
        
        // 保存方案
        val schemeStorage = com.example.show_auto.data.SchemeStorage(context)
        schemeStorage.saveScheme(scheme)
        
        // 调用成功回调
        onImport(scheme)
        
    } catch (e: Exception) {
        showCustomToast(context, "导入失败：${e.message}")
    }
}

/**
 * 从URI获取文件名
 */
private fun getFileNameFromUri(context: android.content.Context, uri: android.net.Uri): String? {
    return try {
        when (uri.scheme) {
            "content" -> {
                val cursor = context.contentResolver.query(uri, null, null, null, null)
                cursor?.use {
                    if (it.moveToFirst()) {
                        val displayNameIndex = it.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
                        if (displayNameIndex != -1) {
                            it.getString(displayNameIndex)
                        } else null
                    } else null
                }
            }
            "file" -> uri.lastPathSegment
            else -> null
        }
    } catch (e: Exception) {
        null
    }
}

/**
 * 显示自定义Toast提示（圆角按钮样式）
 */
private fun showCustomToast(context: android.content.Context, message: String) {
    // 创建自定义布局
    val layout = android.widget.LinearLayout(context).apply {
        orientation = android.widget.LinearLayout.HORIZONTAL
        setPadding(32, 16, 32, 16)
        gravity = android.view.Gravity.CENTER_VERTICAL
        
        // 设置圆角背景和边框
        val backgroundDrawable = android.graphics.drawable.GradientDrawable().apply {
            shape = android.graphics.drawable.GradientDrawable.RECTANGLE
            cornerRadius = 24f // 圆角半径
            setColor(android.graphics.Color.parseColor("#E3F2FD")) // 浅蓝色背景
            setStroke(3, android.graphics.Color.BLACK) // 黑色边框，3px宽度
        }
        background = backgroundDrawable
    }
    
    // 创建消息文本 - 使用黑色，居中显示
    val textView = android.widget.TextView(context).apply {
        text = message
        setTextColor(android.graphics.Color.BLACK) // 黑色文字
        textSize = 16f
        gravity = android.view.Gravity.CENTER
        typeface = android.graphics.Typeface.DEFAULT_BOLD // 加粗字体
    }
    
    // 添加视图到布局
    layout.addView(textView)
    
    // 创建Toast并设置位置
    val toast = Toast(context)
    toast.setGravity(android.view.Gravity.TOP or android.view.Gravity.CENTER_HORIZONTAL, 0, 100)
    toast.duration = Toast.LENGTH_SHORT
    toast.view = layout
    toast.show()
}

/**
 * 动态获取查询顺序：根据用户配置页面的实际设置顺序
 * 这个方法会根据用户在配置页面设置的区域顺序来确定查询优先级
 */
private fun getDynamicQueryOrder(settings: com.example.show_auto.data.SettingsStorage): List<String> {
    // 优先使用统一排序，如果没有则使用旧的配置顺序
    val unifiedOrder = settings.getUnifiedAreaOrder()
    
    if (unifiedOrder.isNotEmpty()) {
        // 使用统一排序，按区域类型分组
        val enabledAreas = mutableListOf<String>()
        val addedAreaTypes = mutableSetOf<String>()
        
        unifiedOrder.forEach { itemId ->
            val areaType = when {
                itemId.startsWith("jade_") -> "jade"
                itemId.startsWith("veg_") -> "veg"
                itemId.startsWith("lab_") -> "lab"
                itemId.startsWith("cond_") -> "cond"
                else -> null
            }
            
            // 如果该区域类型还没有添加过，并且该区域类型是启用的
            if (areaType != null && !addedAreaTypes.contains(areaType)) {
                val isEnabled = when (areaType) {
                    "jade" -> settings.getEnableJadeArea()
                    "veg" -> settings.getEnableVegArea()
                    "lab" -> settings.getEnableLabArea()
                    "cond" -> false // 强制关闭调料区，功能未实现
                    else -> false
                }
                
                if (isEnabled) {
                    val areaName = when (areaType) {
                        "jade" -> "玉片区"
                        "veg" -> "菜地区"
                        "lab" -> "实验室"
                        "cond" -> "调料区"
                        else -> ""
                    }
                    enabledAreas.add(areaName)
                    addedAreaTypes.add(areaType)
                }
            }
        }
        
        // 补充可能缺失的启用区域（统一排序可能不完整）
        if (!addedAreaTypes.contains("jade") && settings.getEnableJadeArea()) {
            enabledAreas.add("玉片区")
        }
        if (!addedAreaTypes.contains("veg") && settings.getEnableVegArea()) {
            enabledAreas.add("菜地区")
        }
        if (!addedAreaTypes.contains("lab") && settings.getEnableLabArea()) {
            enabledAreas.add("实验室")
        }
                        if (!addedAreaTypes.contains("cond") && false) { // 强制关闭调料区，功能未实现
            enabledAreas.add("调料区")
        }
        
        return enabledAreas
    } else {
        // 回退到旧的配置顺序
        val savedOrder = settings.getConfigSectionOrder()
        val enabledAreas = mutableListOf<String>()
        
        if (savedOrder.isNotEmpty()) {
            savedOrder.forEach { sectionId ->
                when (sectionId) {
                    "jade" -> {
                        if (settings.getEnableJadeArea()) {
                            enabledAreas.add("玉片区")
                        }
                    }
                    "veg" -> {
                        if (settings.getEnableVegArea()) {
                            enabledAreas.add("菜地区")
                        }
                    }
                    "cond" -> {
                                    if (false) { // 强制关闭调料区，功能未实现
                enabledAreas.add("调料区")
            }
                    }
                    "lab" -> {
                        if (settings.getEnableLabArea()) {
                            enabledAreas.add("实验室")
                        }
                    }
                }
            }
        } else {
            // 使用默认顺序
            if (settings.getEnableJadeArea()) {
                enabledAreas.add("玉片区")
            }
            if (settings.getEnableVegArea()) {
                enabledAreas.add("菜地区")
            }
            if (false) { // 强制关闭调料区，功能未实现
                enabledAreas.add("调料区")
            }
            if (settings.getEnableLabArea()) {
                enabledAreas.add("实验室")
            }
        }
        
        return enabledAreas
    }
}

/**
 * 根据统一排序获取具体地区的查询配置
 * @param settings 设置存储
 * @param areaType 区域类型（jade, veg, lab）
 * @return 该区域内地区的查询配置列表
 */
private fun getUnifiedAreaConfigs(settings: com.example.show_auto.data.SettingsStorage, areaType: String): List<Any> {
    val unifiedOrder = settings.getUnifiedAreaOrder()
    val configs = mutableListOf<Any>()
    
    if (unifiedOrder.isNotEmpty()) {
        // 按统一排序过滤出指定区域类型的配置
        unifiedOrder.forEach { itemId ->
            if (itemId.startsWith("${areaType}_")) {
                val name = itemId.removePrefix("${areaType}_")
                when (areaType) {
                    "jade" -> {
                        val jadeItemData = getJadeItemData(name)
                        if (jadeItemData != null) {
                            val people = settings.getJadeAreaPeople(name)
                            val capacity = settings.getJadeAreaCapacity(name, 60)
                            if (people > 0) { // 只添加人数大于0的配置
                                configs.add(JadeAreaItem(name, jadeItemData.first, jadeItemData.second, 60, capacity, 5, people))
                            }
                        }
                    }
                    "veg" -> {
                        val vegItemData = getVegItemData(name)
                        if (vegItemData != null) {
                            val people = settings.getVegAreaPeople(name)
                            val capacity = settings.getVegAreaCapacity(name, vegItemData.second)
                            if (people > 0) { // 只添加人数大于0的配置
                                configs.add(VegAreaItem(name, vegItemData.first, vegItemData.second, capacity, 5, people))
                            }
                        }
                    }
                    "lab" -> {
                        if (name in listOf("蒸", "炸", "炒", "煮", "切", "烤")) {
                            val people = settings.getLabAreaPeople(name)
                            val capacity = settings.getLabAreaCapacity(name, 60)
                            if (people > 0) { // 只添加人数大于0的配置
                                configs.add(LabItem(name, people, capacity))
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 如果没有统一排序，回退到旧的排序方式
    if (configs.isEmpty()) {
        when (areaType) {
            "jade" -> return getJadeAreaConfigs(settings)
            "veg" -> return getVegAreaConfigs(settings)
            "lab" -> return emptyList() // 实验室暂时返回空列表
            "cond" -> return getCondAreaConfigs(settings)
        }
    }
    
    return configs
}



@Composable
private fun UnifiedQuerySortingDialog(onDismiss: () -> Unit) {
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }
    val combinationStorage = remember { com.example.show_auto.data.CombinationStorage(context) }
    
    // 监听用户切换，当用户切换时刷新配置
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId() ?: "") }
    
    // 获取当前区域开关状态（只读）
    val enableVeg = settings.getEnableVegArea()
    val enableJade = settings.getEnableJadeArea()
    val enableLab = settings.getEnableLabArea()
    val enableCond = false // 强制关闭调料区，因为功能未实现
    
    // 获取已保存组合的地区名称，用于过滤
    val savedAreaNames = remember(currentUserId) {
        combinationStorage.getAllCombinations()
            .map { it.areaName }
            .toSet()
    }
    
    // 初始化所有地区项目的统一列表
    var allItems by remember(currentUserId, enableVeg, enableJade, enableLab, enableCond, savedAreaNames) {
        mutableStateOf(
            run {
                val items = mutableListOf<UnifiedAreaItem>()
                
                // 获取统一排序
                val unifiedOrder = settings.getUnifiedAreaOrder()
                
                if (unifiedOrder.isNotEmpty()) {
                    // 按保存的统一排序加载，但只加载已启用且未保存组合的区域
                    unifiedOrder.forEach { itemId ->
                        when {
                            itemId.startsWith("jade_") && enableJade -> {
                                val name = itemId.removePrefix("jade_")
                                val jadeItem = getJadeItemData(name)
                                if (jadeItem != null && name !in savedAreaNames) {
                                    items.add(UnifiedAreaItem(
                                        id = itemId,
                                        name = name,
                                        areaType = "jade",
                                        currentPeople = settings.getJadeAreaPeople(name),
                                        currentCapacity = settings.getJadeAreaCapacity(name, 60),
                                        type1 = jadeItem.first,
                                        type2 = jadeItem.second
                                    ))
                                }
                            }
                            itemId.startsWith("veg_") && enableVeg -> {
                                val name = itemId.removePrefix("veg_")
                                val vegItem = getVegItemData(name)
                                if (vegItem != null && name !in savedAreaNames) {
                                    items.add(UnifiedAreaItem(
                                        id = itemId,
                                        name = name,
                                        areaType = "veg",
                                        currentPeople = settings.getVegAreaPeople(name),
                                        currentCapacity = settings.getVegAreaCapacity(name, vegItem.second),
                                        materialType = vegItem.first,
                                        defaultCapacity = vegItem.second
                                    ))
                                }
                            }
                            itemId.startsWith("lab_") && enableLab -> {
                                val name = itemId.removePrefix("lab_")
                                if (name in listOf("蒸", "炸", "炒", "煮", "切", "烤") && name !in savedAreaNames) {
                                    items.add(UnifiedAreaItem(
                                        id = itemId,
                                        name = "${name}技法",
                                        areaType = "lab",
                                        currentPeople = settings.getLabAreaPeople(name),
                                        currentCapacity = settings.getLabAreaCapacity(name, 60)
                                    ))
                                }
                            }
                            itemId.startsWith("cond_") && enableCond -> {
                                val name = itemId.removePrefix("cond_")
                                if (name in listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁") && name !in savedAreaNames) {
                                    items.add(UnifiedAreaItem(
                                        id = itemId,
                                        name = name,
                                        areaType = "cond",
                                        currentPeople = settings.getCondAreaPeople(name),
                                        currentCapacity = settings.getCondAreaCapacity(name, 60)
                                    ))
                                }
                            }
                        }
                    }
                    
                    // 补充缺失的项目（只针对已启用且未保存组合的区域）
                    
                    // 补充缺失的玉片区项目
                    if (enableJade) {
                        val existingJadeIds = items.filter { it.areaType == "jade" }.map { it.id }.toSet()
                        listOf(
                            "藏心亭" to ("肉" to "菜"),
                            "朝阴山" to ("肉" to "面"),
                            "北冥城" to ("鱼" to "面"),
                            "清空谷" to ("肉" to "鱼"),
                            "还寒洞" to ("菜" to "面"),
                            "永昼宫" to ("菜" to "鱼")
                        ).forEach { (name, types) ->
                            val id = "jade_$name"
                            if (id !in existingJadeIds && name !in savedAreaNames) {
                                items.add(UnifiedAreaItem(
                                    id = id,
                                    name = name,
                                    areaType = "jade",
                                    currentPeople = settings.getJadeAreaPeople(name),
                                    currentCapacity = settings.getJadeAreaCapacity(name, 60),
                                    type1 = types.first,
                                    type2 = types.second
                                ))
                            }
                        }
                    }
                    
                    // 补充缺失的菜地区项目
                    if (enableVeg) {
                        val existingVegIds = items.filter { it.areaType == "veg" }.map { it.id }.toSet()
                        listOf(
                            "池塘" to ("鱼" to 29),
                            "菜棚" to ("菜" to 25),
                            "菜地" to ("菜" to 30),
                            "森林" to ("菜" to 32),
                            "牧场" to ("肉" to 25),
                            "猪圈" to ("肉" to 18),
                            "鸡舍" to ("肉" to 24),
                            "作坊" to ("面" to 26)
                        ).forEach { (name, data) ->
                            val id = "veg_$name"
                            if (id !in existingVegIds && name !in savedAreaNames) {
                                items.add(UnifiedAreaItem(
                                    id = id,
                                    name = name,
                                    areaType = "veg",
                                    currentPeople = settings.getVegAreaPeople(name),
                                    currentCapacity = settings.getVegAreaCapacity(name, data.second),
                                    materialType = data.first,
                                    defaultCapacity = data.second
                                ))
                            }
                        }
                    }
                    
                    // 补充缺失的实验室项目
                    if (enableLab) {
                        val existingLabIds = items.filter { it.areaType == "lab" }.map { it.id }.toSet()
                        listOf("蒸", "炸", "炒", "煮", "切", "烤").forEach { name ->
                            val id = "lab_$name"
                            if (id !in existingLabIds && name !in savedAreaNames) {
                                items.add(UnifiedAreaItem(
                                    id = id,
                                    name = "${name}技法",
                                    areaType = "lab",
                                    currentPeople = settings.getLabAreaPeople(name),
                                    currentCapacity = settings.getLabAreaCapacity(name, 60)
                                ))
                            }
                        }
                    }
                    
                    // 补充缺失的调料区项目
                    if (enableCond) {
                        val existingCondIds = items.filter { it.areaType == "cond" }.map { it.id }.toSet()
                        listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁").forEach { name ->
                            val id = "cond_$name"
                            if (id !in existingCondIds && name !in savedAreaNames) {
                                items.add(UnifiedAreaItem(
                                    id = id,
                                    name = name,
                                    areaType = "cond",
                                    currentPeople = settings.getCondAreaPeople(name),
                                    currentCapacity = settings.getCondAreaCapacity(name, 60)
                                ))
                            }
                        }
                    }
                } else {
                    // 使用默认顺序，但要检查启用状态和排除已保存组合的地区
                    // 玉片区项目
                    if (enableJade) {
                        listOf(
                            "藏心亭" to ("肉" to "菜"),
                            "朝阴山" to ("肉" to "面"),
                            "北冥城" to ("鱼" to "面"),
                            "清空谷" to ("肉" to "鱼"),
                            "还寒洞" to ("菜" to "面"),
                            "永昼宫" to ("菜" to "鱼")
                        ).forEach { (name, types) ->
                            if (name !in savedAreaNames) {
                            items.add(UnifiedAreaItem(
                                id = "jade_$name",
                                name = name,
                                areaType = "jade",
                                currentPeople = settings.getJadeAreaPeople(name),
                                currentCapacity = settings.getJadeAreaCapacity(name, 60),
                                type1 = types.first,
                                type2 = types.second
                            ))
                            }
                        }
                    }
                    
                    // 菜地区项目（池塘在最前面）
                    if (enableVeg) {
                        listOf(
                            "池塘" to ("鱼" to 29),
                            "菜棚" to ("菜" to 25),
                            "菜地" to ("菜" to 30),
                            "森林" to ("菜" to 32),
                            "牧场" to ("肉" to 25),
                            "猪圈" to ("肉" to 18),
                            "鸡舍" to ("肉" to 24),
                            "作坊" to ("面" to 26)
                        ).forEach { (name, data) ->
                            if (name !in savedAreaNames) {
                            items.add(UnifiedAreaItem(
                                id = "veg_$name",
                                name = name,
                                areaType = "veg",
                                currentPeople = settings.getVegAreaPeople(name),
                                currentCapacity = settings.getVegAreaCapacity(name, data.second),
                                materialType = data.first,
                                defaultCapacity = data.second
                            ))
                            }
                        }
                    }
                    
                    // 实验室项目
                    if (enableLab) {
                        listOf("蒸", "炸", "炒", "煮", "切", "烤").forEach { name ->
                            if (name !in savedAreaNames) {
                            items.add(UnifiedAreaItem(
                                id = "lab_$name",
                                name = "${name}技法",
                                areaType = "lab",
                                currentPeople = settings.getLabAreaPeople(name),
                                currentCapacity = settings.getLabAreaCapacity(name, 60)
                            ))
                            }
                        }
                    }
                    
                    // 调料区项目
                    if (enableCond) {
                        listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁").forEach { name ->
                            if (name !in savedAreaNames) {
                            items.add(UnifiedAreaItem(
                                id = "cond_$name",
                                name = name,
                                areaType = "cond",
                                currentPeople = settings.getCondAreaPeople(name),
                                currentCapacity = settings.getCondAreaCapacity(name, 60)
                            ))
                            }
                        }
                    }
                }
                
                items
            }
        )
    }
    
    // 监听用户ID变化
    LaunchedEffect(Unit) {
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId() ?: ""
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 重新加载所有配置...
            }
            delay(500)
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(usePlatformDefaultWidth = false),
        title = { 
            Text(
                "优先级排序", 
                fontSize = 16.sp, 
                fontWeight = FontWeight.Bold
            ) 
        },
        text = {
            Column {
                Text(
                    text = "优先级排序（拖拽调整）",
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.padding(bottom = 4.dp)
                )
                
                // 添加提示信息
                if (savedAreaNames.isNotEmpty()) {
                    Text(
                        text = "注意：已保存组合的地区（${savedAreaNames.joinToString("、")}）不会显示在排序列表中",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                } else {
                    Spacer(modifier = Modifier.height(4.dp))
                }
                
                val state = rememberReorderableLazyListState(
                    onMove = { from, to ->
                        allItems = allItems.toMutableList().also { list ->
                            val moved = list.removeAt(from.index)
                            list.add(to.index, moved)
                        }
                        // 保存统一排序
                        settings.saveUnifiedAreaOrder(allItems.map { it.id })
                    },
                    canDragOver = { _, _ -> true },
                    onDragEnd = { _, _ -> }
                )
                
                LazyColumn(
                state = state.listState,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(500.dp)
                    .reorderable(state),
                verticalArrangement = Arrangement.spacedBy(2.dp),
                contentPadding = PaddingValues(vertical = 8.dp)
            ) {
                itemsIndexed(allItems, key = { _, it -> it.id }) { index, item ->
                    ReorderableItem(state, key = item.id) { isDragging ->
                        UnifiedAreaItemRow(
                            item = item,
                            index = index,
                            isDragging = isDragging,
                            onItemUpdate = { newItem ->
                                allItems = allItems.toMutableList().also { list ->
                                    list[index] = newItem
                                }
                                // 保存配置
                                when (newItem.areaType) {
                                    "jade" -> {
                                        settings.saveJadeAreaPeople(newItem.name, newItem.currentPeople)
                                        settings.saveJadeAreaCapacity(newItem.name, newItem.currentCapacity)
                                    }
                                    "veg" -> {
                                        settings.saveVegAreaPeople(newItem.name, newItem.currentPeople)
                                        settings.saveVegAreaCapacity(newItem.name, newItem.currentCapacity)
                                    }
                                    "lab" -> {
                                        settings.saveLabAreaPeople(newItem.name.removeSuffix("技法"), newItem.currentPeople)
                                        settings.saveLabAreaCapacity(newItem.name.removeSuffix("技法"), newItem.currentCapacity)
                                    }
                                    "cond" -> {
                                        settings.saveCondAreaPeople(newItem.name, newItem.currentPeople)
                                        settings.saveCondAreaCapacity(newItem.name, newItem.currentCapacity)
                                    }
                                }
                            },
                            state = state
                        )
                    }
                }
            }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) { 
                Text("关闭") 
            }
        },
        dismissButton = { 
            TextButton(
                onClick = {
                    // 重置为默认顺序：菜地区 -> 玉片区 -> 实验室 -> 调料区（根据启用状态）
                    val defaultOrder = mutableListOf<UnifiedAreaItem>()
                    
                    // 按默认顺序添加菜地区项目（如果启用且未保存组合）
                    if (enableVeg) {
                        listOf("池塘", "菜棚", "菜地", "森林", "牧场", "猪圈", "鸡舍", "作坊").forEach { name ->
                            if (name !in savedAreaNames) {
                            getVegItemData(name)?.let { data ->
                                defaultOrder.add(UnifiedAreaItem(
                                    id = "veg_$name",
                                    name = name,
                                    areaType = "veg",
                                    currentPeople = settings.getVegAreaPeople(name),
                                    currentCapacity = settings.getVegAreaCapacity(name, data.second),
                                    materialType = data.first,
                                    defaultCapacity = data.second
                                ))
                                }
                            }
                        }
                    }
                    
                    // 按默认顺序添加玉片区项目（如果启用且未保存组合）
                    if (enableJade) {
                        listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫").forEach { name ->
                            if (name !in savedAreaNames) {
                            getJadeItemData(name)?.let { jadeItemData ->
                                defaultOrder.add(UnifiedAreaItem(
                                    id = "jade_$name",
                                    name = name,
                                    areaType = "jade",
                                    currentPeople = settings.getJadeAreaPeople(name),
                                    currentCapacity = settings.getJadeAreaCapacity(name, 60),
                                    type1 = jadeItemData.first,
                                    type2 = jadeItemData.second
                                ))
                                }
                            }
                        }
                    }
                    
                    // 按默认顺序添加实验室项目（如果启用且未保存组合）
                    if (enableLab) {
                        listOf("蒸", "炸", "炒", "煮", "切", "烤").forEach { name ->
                            if (name !in savedAreaNames) {
                            defaultOrder.add(UnifiedAreaItem(
                                id = "lab_$name",
                                name = "${name}技法",
                                areaType = "lab",
                                currentPeople = settings.getLabAreaPeople(name),
                                currentCapacity = settings.getLabAreaCapacity(name, 60)
                            ))
                            }
                        }
                    }
                    
                    // 按默认顺序添加调料区项目（如果启用且未保存组合）
                    if (enableCond) {
                        listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁").forEach { name ->
                            if (name !in savedAreaNames) {
                            defaultOrder.add(UnifiedAreaItem(
                                id = "cond_$name",
                                name = name,
                                areaType = "cond",
                                currentPeople = settings.getCondAreaPeople(name),
                                currentCapacity = settings.getCondAreaCapacity(name, 60)
                            ))
                            }
                        }
                    }
                    
                    allItems = defaultOrder
                    // 保存重置后的顺序
                    settings.saveUnifiedAreaOrder(allItems.map { it.id })
                }
            ) {
                Text("重置")
            }
        }
    )
}

// 辅助函数：获取玉片区项目数据
private fun getJadeItemData(name: String): Pair<String, String>? {
    return when (name) {
        "藏心亭" -> "肉" to "菜"
        "朝阴山" -> "肉" to "面"
        "北冥城" -> "鱼" to "面"
        "清空谷" -> "肉" to "鱼"
        "还寒洞" -> "菜" to "面"
        "永昼宫" -> "菜" to "鱼"
        else -> null
    }
}

// 辅助函数：获取菜地区项目数据
private fun getVegItemData(name: String): Pair<String, Int>? {
    return when (name) {
        "菜棚" -> "菜" to 25
        "菜地" -> "菜" to 30
        "森林" -> "菜" to 32
        "牧场" -> "肉" to 25
        "猪圈" -> "肉" to 18
        "鸡舍" -> "肉" to 24
        "作坊" -> "面" to 26
        "池塘" -> "鱼" to 29
        else -> null
    }
}

// 统一的地区项目数据结构（用于跨区域拖拽排序）
data class UnifiedAreaItem(
    val id: String, // 唯一标识
    val name: String, // 显示名称
    val areaType: String, // 区域类型：jade, veg, lab
    val currentPeople: Int,
    val currentCapacity: Int,
    val type1: String = "", // 玉片区的第一种类型
    val type2: String = "", // 玉片区的第二种类型
    val materialType: String = "", // 菜地区的素材类型
    val defaultCapacity: Int = 60 // 菜地区的默认采集点
)

@Composable
private fun UnifiedAreaItemRow(
    item: UnifiedAreaItem,
    index: Int,
    isDragging: Boolean,
    onItemUpdate: (UnifiedAreaItem) -> Unit,
    state: ReorderableLazyListState
) {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp, vertical = 2.dp),
        color = when (item.areaType) {
            "jade" -> Color(0xFFFFF3E0) // 浅橙色背景
            "veg" -> Color(0xFFE8F5E8) // 浅绿色背景
            "lab" -> Color(0xFFE3F2FD) // 浅蓝色背景
            "cond" -> Color(0xFFF3E5F5) // 浅紫色背景
            else -> Color(0xFFF5F5F5)
        },
        shape = RoundedCornerShape(8.dp),
        shadowElevation = if (isDragging) 6.dp else 0.dp
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp, vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Row(
                modifier = Modifier.weight(1f),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                // 区域类型标识
                Text(
                    text = when (item.areaType) {
                        "jade" -> "玉"
                        "veg" -> "菜"
                        "lab" -> "实"
                        "cond" -> "料"
                        else -> "?"
                    },
                    fontSize = 10.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    modifier = Modifier
                        .background(
                            color = when (item.areaType) {
                                "jade" -> Color(0xFFFF9800) // 橙色
                                "veg" -> Color(0xFF4CAF50) // 绿色
                                "lab" -> Color(0xFF2196F3) // 蓝色
                                "cond" -> Color(0xFF9C27B0) // 紫色
                                else -> Color.Gray
                            },
                            shape = RoundedCornerShape(4.dp)
                        )
                        .padding(horizontal = 4.dp, vertical = 2.dp)
                )

                // 地点名称（带颜色，固定宽度确保竖线对齐）
                Text(
                    text = item.name,
                    fontSize = 12.sp,
                    color = when {
                        item.areaType == "jade" -> when (item.name) {
                            "朝阴山" -> Color.Black
                            "永昼宫" -> Color.Red
                            "还寒洞" -> Color.Blue
                            "北冥城" -> Color(0xFFFFA500) // 橙色/黄色
                            "藏心亭" -> Color(0xFFFF69B4) // 粉色
                            "清空谷" -> Color(0xFF00AA00) // 绿色
                            else -> MaterialTheme.colorScheme.onSurface
                        }
                        item.areaType == "veg" -> when (item.materialType) {
                            "鱼" -> Color.Blue
                            "肉" -> Color.Red
                            "菜" -> Color(0xFF00AA00) // 绿色
                            "面" -> Color(0xFFFFA500) // 黄色
                            else -> MaterialTheme.colorScheme.onSurface
                        }
                        item.areaType == "lab" -> when (item.name) {
                            "蒸" -> Color(0xFFFFA500) // 橙色/黄色（与北冥城相同）
                            "炸" -> Color(0xFF2196F3) // 蓝色
                            "炒" -> Color(0xFFF44336) // 红色
                            "煮" -> Color(0xFF4CAF50) // 绿色
                            "切" -> Color(0xFF795548) // 棕色
                            "烤" -> Color(0xFF9C27B0) // 紫色
                            else -> MaterialTheme.colorScheme.onSurface
                        }
                        item.areaType == "cond" -> when (item.name) {
                            "樊正阁" -> Color(0xFFE91E63) // 粉红色
                            "庖丁阁" -> Color(0xFF9C27B0) // 紫色
                            "膳祖阁" -> Color(0xFF673AB7) // 深紫色
                            "易牙阁" -> Color(0xFF3F51B5) // 靛蓝色
                            "彭铿阁" -> Color(0xFF2196F3) // 蓝色
                            "伊尹阁" -> Color(0xFF009688) // 蓝绿色
                            else -> MaterialTheme.colorScheme.onSurface
                        }
                        else -> MaterialTheme.colorScheme.onSurface
                    },
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.width(56.dp) // 固定宽度确保竖线对齐
                )

                Text(
                    text = "｜",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )

                Text(
                    text = "人数",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )

                // 人数下拉框
                SmallDropdownField(
                    value = item.currentPeople,
                    onValueChange = { newValue ->
                        onItemUpdate(item.copy(currentPeople = newValue))
                    },
                    options = listOf(5, 4, 3, 2, 1, 0),
                    widthDp = 30.dp
                )

                // 采集点下拉框（根据地区类型使用不同组件，实验室不显示采集点）
                if (item.areaType != "lab") {
                Text(
                    text = "采集点",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )

                when (item.areaType) {
                    "jade" -> {
                        SmallDropdownField(
                            value = item.currentCapacity,
                            onValueChange = { newValue ->
                                onItemUpdate(item.copy(currentCapacity = newValue))
                            },
                            options = (165 downTo 15 step 15).toList(),
                            widthDp = 45.dp
                        )
                    }
                    "veg" -> {
                        CollectionDropdownField(
                            value = item.currentCapacity,
                            onValueChange = { newValue ->
                                onItemUpdate(item.copy(currentCapacity = newValue))
                            },
                            areaName = item.name,
                            widthDp = 45.dp
                        )
                    }
                    "cond" -> {
                        SmallDropdownField(
                            value = item.currentCapacity,
                            onValueChange = { newValue ->
                                onItemUpdate(item.copy(currentCapacity = newValue))
                            },
                            options = listOf(60),
                            widthDp = 45.dp
                        )
                        }
                    }
                }
            }

            Icon(
                imageVector = Icons.Default.Menu,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier.detectReorder(state)
            )
        }
    }
}

// 旧版本的JadeAreaConfigContent - 已被UnifiedQuerySortingDialog替代
@Composable
private fun JadeAreaConfigContent(settings: com.example.show_auto.data.SettingsStorage, currentUserId: String) {
    data class JadeItem(val name: String, val type1: String, val type2: String, val currentPeople: Int, val currentCapacity: Int)
    val jadeDefaultItems = listOf(
        JadeItem("藏心亭", "肉", "菜", 5, 60),
        JadeItem("朝阴山", "肉", "面", 5, 60),
        JadeItem("北冥城", "鱼", "面", 5, 60),
        JadeItem("清空谷", "肉", "鱼", 5, 60),
        JadeItem("还寒洞", "菜", "面", 5, 60),
        JadeItem("永昼宫", "菜", "鱼", 5, 60)
    )
    
    var items by remember(currentUserId) {
        mutableStateOf(
            run {
                val savedOrder = settings.getJadeAreaOrder()
                val ordered = if (savedOrder.isEmpty()) jadeDefaultItems.map { it.name } else savedOrder.filter { it in jadeDefaultItems.map { item -> item.name } } + jadeDefaultItems.map { it.name }.filter { it !in savedOrder }
                ordered.map { name ->
                    val item = jadeDefaultItems.find { it.name == name } ?: jadeDefaultItems.first()
                    val people = settings.getJadeAreaPeople(name)
                    val capacity = settings.getJadeAreaCapacity(name, 60).coerceAtMost(300)
                    JadeItem(name = name, type1 = item.type1, type2 = item.type2, currentPeople = people, currentCapacity = capacity)
                }
            }
        )
    }
    
    val state = rememberReorderableLazyListState(onMove = { from, to ->
        items = items.toMutableList().also { list ->
            val moved = list.removeAt(from.index)
            list.add(to.index, moved)
        }
        settings.saveJadeAreaOrder(items.map { it.name })
    })
    
    LazyColumn(
        state = state.listState,
        modifier = Modifier.reorderable(state)
    ) {
        itemsIndexed(items, key = { _, it -> it.name }) { index, item ->
            ReorderableItem(state, key = item.name) { isDragging ->
                Surface(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 8.dp, vertical = 2.dp),
                    color = Color(0xFFE3F2FD),
                    shape = RoundedCornerShape(8.dp),
                    shadowElevation = if (isDragging) 6.dp else 0.dp
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 12.dp, vertical = 6.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Row(
                            modifier = Modifier.weight(1f),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            Text(
                                text = item.name,
                                fontSize = 12.sp,
                                color = when (item.name) {
                                    "朝阴山" -> Color.Black
                                    "永昼宫" -> Color.Red
                                    "还寒洞" -> Color.Blue
                                    "北冥城" -> Color(0xFFFFA500) // 橙色/黄色
                                    "藏心亭" -> Color(0xFFFF69B4) // 粉色
                                    "清空谷" -> Color(0xFF00AA00) // 绿色
                                    else -> MaterialTheme.colorScheme.onPrimaryContainer
                                },
                                fontWeight = FontWeight.Medium
                            )

                            Text(
                                text = "｜",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            Text(
                                text = "人数",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            SmallDropdownField(
                                value = item.currentPeople,
                                onValueChange = { newValue ->
                                    items = items.toMutableList().also { list ->
                                        list[index] = item.copy(currentPeople = newValue)
                                    }
                                    settings.saveJadeAreaPeople(item.name, newValue)
                                },
                                options = listOf(5, 4, 3, 2, 1, 0),
                                widthDp = 30.dp
                            )

                            Text(
                                text = "采集点",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            SmallDropdownField(
                                value = item.currentCapacity,
                                onValueChange = { newValue ->
                                    items = items.toMutableList().also { list ->
                                        list[index] = item.copy(currentCapacity = newValue)
                                    }
                                    settings.saveJadeAreaCapacity(item.name, newValue)
                                },
                                options = (165 downTo 15 step 15).toList(),
                                widthDp = 45.dp
                            )
                        }

                        Icon(
                            imageVector = Icons.Default.Menu,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.detectReorder(state)
                        )
                    }
                }
            }
            if (index < items.lastIndex) {
                HorizontalDivider()
            }
        }
    }
}

@Composable
private fun VegAreaConfigContent(settings: com.example.show_auto.data.SettingsStorage, currentUserId: String) {
    data class VegItem(val name: String, val type: String, val defaultCapacity: Int, val currentPeople: Int, val currentCapacity: Int)
    val vegDefaultItems = listOf(
        VegItem("菜棚", "菜", 25, 5, 25),
        VegItem("菜地", "菜", 30, 5, 30),
        VegItem("森林", "菜", 32, 5, 32),
        VegItem("牧场", "肉", 25, 5, 25),
        VegItem("猪圈", "肉", 18, 5, 18),
        VegItem("鸡舍", "肉", 24, 5, 24),
        VegItem("作坊", "面", 26, 5, 26),
        VegItem("池塘", "鱼", 29, 5, 29)
    )
    
    var items by remember(currentUserId) {
        mutableStateOf(
            run {
                val savedOrder = settings.getVegAreaOrder()
                val ordered = if (savedOrder.isEmpty()) vegDefaultItems else savedOrder.mapNotNull { savedName ->
                    vegDefaultItems.find { it.name == savedName }
                } + vegDefaultItems.filter { item -> item.name !in savedOrder }
                ordered.map { item ->
                    val savedPeople = settings.getVegAreaPeople(item.name)
                    val savedCapacity = settings.getVegAreaCapacity(item.name, item.defaultCapacity)
                    item.copy(currentPeople = savedPeople, currentCapacity = savedCapacity)
                }
            }
        )
    }
    
    val state = rememberReorderableLazyListState(onMove = { from, to ->
        items = items.toMutableList().also { list ->
            val moved = list.removeAt(from.index)
            list.add(to.index, moved)
        }
        settings.saveVegAreaOrder(items.map { it.name })
    })
    
    LazyColumn(
        state = state.listState,
        modifier = Modifier.reorderable(state)
    ) {
        itemsIndexed(items, key = { _, it -> it.name }) { index, item ->
            ReorderableItem(state, key = item.name) { isDragging ->
                Surface(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 8.dp, vertical = 2.dp),
                    color = Color(0xFFE3F2FD),
                    shape = RoundedCornerShape(8.dp),
                    shadowElevation = if (isDragging) 6.dp else 0.dp
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 12.dp, vertical = 6.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Row(
                            modifier = Modifier.weight(1f),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            Text(
                                text = item.name,
                                fontSize = 12.sp,
                                color = when (item.name) {
                                    "池塘" -> Color.Blue
                                    "牧场", "猪圈", "鸡舍" -> Color.Red
                                    "菜棚", "菜地", "森林" -> Color(0xFF00AA00) // 绿色
                                    "作坊" -> Color(0xFFFFA500) // 黄色
                                    else -> MaterialTheme.colorScheme.onPrimaryContainer
                                },
                                fontWeight = FontWeight.Medium
                            )

                            Text(
                                text = "｜",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            Text(
                                text = "人数",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            SmallDropdownField(
                                value = item.currentPeople,
                                onValueChange = { newValue ->
                                    items = items.toMutableList().also { list ->
                                        list[index] = item.copy(currentPeople = newValue)
                                    }
                                    settings.saveVegAreaPeople(item.name, newValue)
                                },
                                options = listOf(5, 4, 3, 2, 1, 0),
                                widthDp = 30.dp
                            )

                            Text(
                                text = "采集点",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            CollectionDropdownField(
                                value = item.currentCapacity,
                                onValueChange = { newValue ->
                                    items = items.toMutableList().also { list ->
                                        list[index] = item.copy(currentCapacity = newValue)
                                    }
                                    settings.saveVegAreaCapacity(item.name, newValue)
                                },
                                areaName = item.name,
                                widthDp = 40.dp
                            )
                        }

                        Icon(
                            imageVector = Icons.Default.Menu,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.detectReorder(state)
                        )
                    }
                }
            }
            if (index < items.lastIndex) {
                HorizontalDivider()
            }
        }
    }
}

@Composable
private fun LabAreaConfigContent(settings: com.example.show_auto.data.SettingsStorage, currentUserId: String) {
    val labDefaultNames = listOf("蒸", "炸", "炒", "煮", "切", "烤")
    
    var items by remember(currentUserId) {
        mutableStateOf(
            run {
                val savedOrder = settings.getLabAreaOrder()
                val ordered = if (savedOrder.isEmpty()) labDefaultNames else savedOrder.filter { it in labDefaultNames } + labDefaultNames.filter { it !in savedOrder }
                ordered.map { name ->
                    val people = settings.getLabAreaPeople(name)
                    val capacity = settings.getLabAreaCapacity(name, 60).coerceAtMost(300)
                    LabItem(name = "${name}技法", currentPeople = people, currentCapacity = capacity)
                }
            }
        )
    }
    
    val state = rememberReorderableLazyListState(onMove = { from, to ->
        items = items.toMutableList().also { list ->
            val moved = list.removeAt(from.index)
            list.add(to.index, moved)
        }
        settings.saveLabAreaOrder(items.map { it.name })
    })
    
    LazyColumn(
        state = state.listState,
        modifier = Modifier.reorderable(state)
    ) {
        itemsIndexed(items, key = { _, it -> it.name }) { index, item ->
            ReorderableItem(state, key = item.name) { isDragging ->
                Surface(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 8.dp, vertical = 2.dp),
                    color = Color(0xFFE3F2FD),
                    shape = RoundedCornerShape(8.dp),
                    shadowElevation = if (isDragging) 6.dp else 0.dp
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 12.dp, vertical = 6.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Row(
                            modifier = Modifier.weight(1f),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            Text(
                                text = item.name,
                                fontSize = 12.sp,
                                color = when (item.name.removeSuffix("技法")) {
                                    "蒸" -> Color(0xFFFFA500) // 橙色/黄色（与北冥城相同）
                                    "炸" -> Color(0xFF2196F3) // 蓝色
                                    "炒" -> Color(0xFFF44336) // 红色
                                    "煮" -> Color(0xFF4CAF50) // 绿色
                                    "切" -> Color(0xFF795548) // 棕色
                                    "烤" -> Color(0xFF9C27B0) // 紫色
                                    else -> MaterialTheme.colorScheme.onPrimaryContainer
                                },
                                fontWeight = FontWeight.Medium
                            )

                            Text(
                                text = "｜",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            Text(
                                text = "人数",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            SmallDropdownField(
                                value = item.currentPeople,
                                onValueChange = { newValue ->
                                    items = items.toMutableList().also { list ->
                                        list[index] = item.copy(currentPeople = newValue)
                                    }
                                    settings.saveLabAreaPeople(item.name.removeSuffix("技法"), newValue)
                                },
                                options = listOf(5, 4, 3, 2, 1, 0),
                                widthDp = 30.dp
                            )

                            Text(
                                text = "采集点",
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )

                            SmallDropdownField(
                                value = item.currentCapacity,
                                onValueChange = { newValue ->
                                    items = items.toMutableList().also { list ->
                                        list[index] = item.copy(currentCapacity = newValue)
                                    }
                                    settings.saveLabAreaCapacity(item.name.removeSuffix("技法"), newValue)
                                },
                                options = listOf(60),
                                widthDp = 45.dp
                            )
                        }

                        Icon(
                            imageVector = Icons.Default.Menu,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.detectReorder(state)
                        )
                    }
                }
            }
            if (index < items.lastIndex) {
                HorizontalDivider()
            }
        }
    }
}

@Composable
private fun LabAreaConfigDialog(onDismiss: () -> Unit) {
    val context = LocalContext.current
    val settings = remember { com.example.show_auto.data.SettingsStorage(context) }

    // 监听用户切换，当用户切换时刷新配置
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId()) }
    
    // 实验室域配置（蒸、炸、炒、煮、切、烤）
    val defaultNames = listOf("蒸", "炸", "炒", "煮", "切", "烤")
    var items by remember(currentUserId) {
        mutableStateOf(
            run {
                val savedOrder = settings.getLabAreaOrder()
                val ordered = if (savedOrder.isEmpty()) defaultNames else savedOrder.filter { it in defaultNames } + defaultNames.filter { it !in savedOrder }
                ordered.map { name ->
                    val people = settings.getLabAreaPeople(name)
                    val capacity = settings.getLabAreaCapacity(name, 60).coerceAtMost(300)
                    LabItem(name = "${name}技法", currentPeople = people, currentCapacity = capacity)
                }
            }
        )
    }
    
    // 监听用户ID变化
    LaunchedEffect(Unit) {
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId()
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 用户切换了，重新加载配置
                val savedOrder = settings.getLabAreaOrder()
                val ordered = if (savedOrder.isEmpty()) defaultNames else savedOrder.filter { it in defaultNames } + defaultNames.filter { it !in savedOrder }
                items = ordered.map { name ->
                    val people = settings.getLabAreaPeople(name)
                    val capacity = settings.getLabAreaCapacity(name, 60).coerceAtMost(300)
                    LabItem(name = "${name}技法", currentPeople = people, currentCapacity = capacity)
                }
            }
            delay(500) // 每500毫秒检查一次
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("拖动调整查询优先级（顺序权重）", fontSize = 16.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis) },
        text = {
            val state = rememberReorderableLazyListState(onMove = { from, to ->
                items = items.toMutableList().also { list ->
                    val moved = list.removeAt(from.index)
                    list.add(to.index, moved)
                }
                settings.saveLabAreaOrder(items.map { it.name })
            })
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 500.dp),
                colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
            ) {
                LazyColumn(
                    state = state.listState,
                    modifier = Modifier.reorderable(state)
                ) {
                    itemsIndexed(items, key = { _, it -> it.name }) { index, item ->
                        ReorderableItem(state, key = item.name) { isDragging ->
                            Surface(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 8.dp, vertical = 2.dp),
                                color = Color(0xFFE3F2FD),
                                shape = RoundedCornerShape(8.dp),
                                shadowElevation = if (isDragging) 6.dp else 0.dp
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 12.dp, vertical = 6.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Row(
                                        modifier = Modifier.weight(1f),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                                                                 Text(
                                             text = item.name,
                                             fontSize = 12.sp,
                                             color = when (item.name.removeSuffix("技法")) {
                                                 "蒸" -> Color(0xFFFFA500) // 橙色/黄色（与北冥城相同）
                                                 "炸" -> Color(0xFF2196F3) // 蓝色
                                                 "炒" -> Color(0xFFF44336) // 红色
                                                 "煮" -> Color(0xFF4CAF50) // 绿色
                                                 "切" -> Color(0xFF795548) // 棕色
                                                 "烤" -> Color(0xFF9C27B0) // 紫色
                                                 else -> MaterialTheme.colorScheme.onPrimaryContainer
                                             },
                                             fontWeight = FontWeight.Medium
                                         )

                                        Text(
                                            text = "｜",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        Text(
                                            text = "人数",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // 人数下拉框（选项：5, 4, 3, 2, 1, 0，0表示跳过该区域）
                                        SmallDropdownField(
                                            value = item.currentPeople,
                                            onValueChange = { newValue ->
                                                items = items.toMutableList().also { list ->
                                                    list[index] = item.copy(currentPeople = newValue)
                                                }
                                                // 自动保存人数配置
                                                settings.saveLabAreaPeople(item.name.removeSuffix("技法"), newValue)
                                            },
                                            options = listOf(5, 4, 3, 2, 1, 0),
                                            widthDp = 30.dp
                                        )

                                        Text(
                                            text = "采集点",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )

                                        // 采集点下拉框（目前只有一档，默认60）
                                        SmallDropdownField(
                                            value = item.currentCapacity,
                                            onValueChange = { newValue ->
                                                items = items.toMutableList().also { list ->
                                                    list[index] = item.copy(currentCapacity = newValue)
                                                }
                                                // 自动保存采集点配置
                                                settings.saveLabAreaCapacity(item.name.removeSuffix("技法"), newValue)
                                            },
                                            options = listOf(60), // 先默认为60一个选项
                                            widthDp = 45.dp
                                        )
                                    }

                                    Icon(
                                        imageVector = Icons.Default.Menu,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.primary,
                                        modifier = Modifier.detectReorder(state)
                                    )
                                }
                            }
                        }
                        if (index < items.lastIndex) {
                            HorizontalDivider()
                        }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = { TextButton(onClick = onDismiss) { Text("关闭") } }
    )
}

/**
 * 处理单个菜地区地区的查询
 */
private fun processVegAreaSingle(
    areaName: String,
    gameData: GameData,
    availableChefs: MutableList<Chef>,
    personalData: PersonalData?,
    settings: com.example.show_auto.data.SettingsStorage,
    allResults: MutableList<ChefResult>
) {
    val people = settings.getVegAreaPeople(areaName)
    // 获取正确的默认容量值
    val defaultCapacity = getVegItemData(areaName)?.second ?: 30
    val capacity = settings.getVegAreaCapacity(areaName, defaultCapacity)
    
    if (people <= 0) return
    
    val silverShoesEnabled = settings.getUseSilverShoes()
    val useMaxLevelAmber = settings.getUseMaxLevelAmber()
    
    
    // 创建单个地区的配置
    val vegItem = getVegItemData(areaName)
    if (vegItem != null) {
        val singleAreaConfig = listOf(VegAreaItem(areaName, vegItem.first, vegItem.second, capacity, 5, people))
        
        val vegResults = CollectionTeamCalculator.calculateVegAreaResults(
            gameData = gameData.copy(chefs = availableChefs),
            personalData = personalData,
            vegEnabled = true,
            vegAreaConfigs = singleAreaConfig,
            useSilverShoes = silverShoesEnabled,
            useMaxLevelAmber = useMaxLevelAmber,
            useAllUltimateTraining = settings.getUseAllUltimateTraining(),
            useAllChefs = settings.getCalculatorUseAllChefs()
        ).map { result ->
            val chef = availableChefs.find { it.name == result.chefName }
            if (chef != null) {
                val targetType = when (result.area) {
                    "池塘" -> "鱼"
                    "牧场", "猪圈", "鸡舍" -> "肉"
                    "菜棚", "菜地", "森林" -> "菜"
                    "作坊" -> "面"
                    else -> ""
                }
                        val separatedSkills = CollectionTeamCalculator.calculateSeparatedSkillBonus(
            chef, gameData, personalData, targetType, silverShoesEnabled, useMaxLevelAmber, false, settings.getUseAllUltimateTraining()
        )
                
                // 从可用厨师池中移除已使用的厨师
                availableChefs.removeAll { it.name == result.chefName }
                
                ChefResultWithSkills(
                    chefName = result.chefName,
                    chefRarity = result.rarity,
                    chefTimeSeconds = result.timeEfficiency,
                    chefOwned = result.owned,
                    chefArea = result.area,
                    chefCollectionDetails = "肉:${result.collectionStats.meat} 鱼:${result.collectionStats.fish} 菜:${result.collectionStats.veg} 面:${result.collectionStats.creation}",
                    chefIsUltimate = chef.ult,
                    critChance = separatedSkills.totalCritChance,
                    critMaterial = separatedSkills.totalCritMaterial,
                    materialGain = separatedSkills.totalMaterialGain,
                    baseMeat = chef.meat,
                    baseFish = chef.fish,
                    baseVeg = chef.veg,
                    baseCreation = chef.creation,
                    totalMeat = result.collectionStats.meat,
                    totalFish = result.collectionStats.fish,
                    totalVeg = result.collectionStats.veg,
                    totalCreation = result.collectionStats.creation
                )
            } else {
                ChefResult(
                    name = result.chefName,
                    rarity = result.rarity,
                    timeSeconds = result.timeEfficiency,
                    owned = result.owned,
                    area = result.area,
                    collectionDetails = "肉:${result.collectionStats.meat} 鱼:${result.collectionStats.fish} 菜:${result.collectionStats.veg} 面:${result.collectionStats.creation}",
                    isUltimate = false
                )
            }
        }
        allResults.addAll(vegResults)
    }
}

/**
 * 处理单个玉片区地区的查询
 */
private fun processJadeAreaSingle(
    areaName: String,
    gameData: GameData,
    availableChefs: MutableList<Chef>,
    personalData: PersonalData?,
    settings: com.example.show_auto.data.SettingsStorage,
    allResults: MutableList<ChefResult>,
    useSilverShoes: Boolean = false,
    useMaxLevelAmber: Boolean = false
) {
    val people = settings.getJadeAreaPeople(areaName)
    val capacity = settings.getJadeAreaCapacity(areaName, 60) // 默认容量60
    
    if (people <= 0) return
    
    // 获取地区要求的两种采集类型
    val jadeItem = getJadeItemData(areaName)
    if (jadeItem == null) return
    
    val requiredTypes = setOf(jadeItem.first, jadeItem.second)
    
    
    // 预过滤厨师：只保留原始采集点（含技能加成）匹配的厨师
    val matchedChefs = availableChefs.filter { chef ->
        // 计算包含厨师技能加成的原始采集点
        val baseCollectionPoints = calculateChefBaseCollectionPoints(chef, gameData, personalData)
        
        // 找到该厨师原始采集点最高的两个类型
        val topTwoTypes = baseCollectionPoints
            .toList()
            .sortedByDescending { it.second }
            .take(2)
            .map { it.first }
            .toSet()
        
        // 判断是否匹配：厨师的前两个优势类型必须与地区要求一致
        val isMatched = topTwoTypes == requiredTypes
        
        if (isMatched) {

        }
        
        isMatched
    }
    
    if (matchedChefs.isEmpty()) {
        return
    }
    
    // 创建单个地区的配置，只使用匹配的厨师
    val singleAreaConfig = listOf(JadeAreaItem(areaName, jadeItem.first, jadeItem.second, 60, capacity, 5, people))
    

    
    val jadeResults = CollectionTeamCalculator.calculateJadeAreaResults(
        gameData = gameData.copy(chefs = matchedChefs), // 只使用匹配的厨师
        personalData = personalData,
        jadeEnabled = true,
        jadeAreaConfigs = singleAreaConfig,
        useSilverShoes = useSilverShoes,
        useMaxLevelAmber = useMaxLevelAmber,
        useAllUltimateTraining = settings.getUseAllUltimateTraining(),
        useAllChefs = settings.getCalculatorUseAllChefs()
    ).map { result ->
        val chef = matchedChefs.find { it.name == result.chefName }
        if (chef != null) {
            val (targetType, dualTypeInfo) = when (result.area) {
                "藏心亭" -> "肉" to "肉+菜:${result.totalCapacity}"
                "朝阴山" -> "肉" to "肉+面:${result.totalCapacity}"
                "北冥城" -> "鱼" to "鱼+面:${result.totalCapacity}"
                "清空谷" -> "肉" to "肉+鱼:${result.totalCapacity}"
                "还寒洞" -> "菜" to "菜+面:${result.totalCapacity}"
                "永昼宫" -> "菜" to "菜+鱼:${result.totalCapacity}"
                else -> "" to ""
            }

            val separatedSkills = CollectionTeamCalculator.calculateSeparatedSkillBonus(
                chef, gameData, personalData, targetType, useSilverShoes, useMaxLevelAmber, true, settings.getUseAllUltimateTraining()
            )
            
            // 从可用厨师池中移除已使用的厨师
            availableChefs.removeAll { it.name == result.chefName }
            
            ChefResultWithSkills(
                chefName = result.chefName,
                chefRarity = result.rarity,
                chefTimeSeconds = result.timeEfficiency,
                chefOwned = result.owned,
                chefArea = result.area,
                chefCollectionDetails = dualTypeInfo,
                chefIsUltimate = chef.ult,
                critChance = separatedSkills.totalCritChance,
                critMaterial = separatedSkills.totalCritMaterial,
                materialGain = separatedSkills.totalMaterialGain,
                baseMeat = chef.meat,
                baseFish = chef.fish,
                baseVeg = chef.veg,
                baseCreation = chef.creation,
                totalMeat = result.collectionStats.meat,
                totalFish = result.collectionStats.fish,
                totalVeg = result.collectionStats.veg,
                totalCreation = result.collectionStats.creation
            )
        } else {
            ChefResult(
                name = result.chefName,
                rarity = result.rarity,
                timeSeconds = result.timeEfficiency,
                owned = result.owned,
                area = result.area,
                collectionDetails = "双类型采集点:${result.totalCapacity}",
                isUltimate = false
            )
        }
    }
    allResults.addAll(jadeResults)
}

/**
 * 处理单个实验室地区的查询
 */
private fun processLabAreaSingle(
    areaName: String,
    gameData: GameData,
    availableChefs: MutableList<Chef>,
    personalData: PersonalData?,
    settings: com.example.show_auto.data.SettingsStorage,
    allResults: MutableList<ChefResult>,
    context: android.content.Context? = null
) {
    val people = settings.getLabAreaPeople(areaName)
    val capacity = settings.getLabAreaCapacity(areaName, 60)
    
    if (people <= 0) return
    
    // 创建实验室地区配置
    val labConfig = CollectionTeamCalculator.LabAreaItem(areaName, people)
    
    println("DEBUG: processLabAreaSingle - 地区: $areaName, 可用厨师数量: ${availableChefs.size}")
    
    // 检查孙武是否在可用厨师中
    val sunwu = availableChefs.find { it.name == "孙武" }
    if (sunwu != null) {
        println("DEBUG: 孙武在可用厨师中 - 切:${sunwu.knife}, 炒:${sunwu.stirfry}")
    } else {
        println("DEBUG: 孙武不在可用厨师中")
    }
    
    // 调用实验室计算函数
    val labResults = CollectionTeamCalculator.calculateLabAreaResults(
        gameData = gameData.copy(chefs = availableChefs),
        personalData = personalData,
        labEnabled = true,
        labAreaConfigs = listOf(labConfig),
        useLabEquip150 = settings.getUseLabEquip150(),
        useBeginnerEquip100 = settings.getUseBeginnerEquip100(),
        useMaxLevelAmber = settings.getUseMaxLevelAmber(),
        useAllChefs = settings.getCalculatorUseAllChefs(),
        excludedChefIds = emptySet(), // 暂时为空，后续可以从设置中获取
        savedCombinationChefIds = emptySet(), // 暂时为空，后续可以从设置中获取
        enabledAuraChefs = getEnabledAuraChefs(gameData, personalData, settings, context), // 获取当前用户的光环厨师
        context = context,
        useAllUltimateTraining = settings.getUseAllUltimateTraining()
    )
    
    // 转换结果为ChefResult格式
    labResults.forEach { result ->
        // 查找对应的厨师数据
        val chef = availableChefs.find { it.name == result.chefName }
        if (chef != null) {
            // 根据地区名称确定技法类型
            val skillType = when (areaName) {
                "蒸技法" -> "蒸"
                "炸技法" -> "炸"
                "炒技法" -> "炒"
                "煮技法" -> "煮"
                "切技法" -> "切"
                "烤技法" -> "烤"
                else -> areaName
            }
            
            // 计算该厨师在指定技法类型的技法值
            val skillStats = CollectionTeamCalculator.calculateChefSkillStats(
                chef = chef,
                gameData = gameData,
                personalData = personalData,
                useLabEquip150 = settings.getUseLabEquip150(),
                useBeginnerEquip100 = settings.getUseBeginnerEquip100(),
                useMaxLevelAmber = settings.getUseMaxLevelAmber(),
                context = context,
                useAllUltimateTraining = settings.getUseAllUltimateTraining(),
                targetSkillType = skillType
            )
            
            val skillValue = skillStats.getSkillValue(skillType)
            
            // 构建详细信息，包含光环信息
            val detailsBuilder = StringBuilder()
            detailsBuilder.append("${skillType}技法值: $skillValue")
            
            // 获取当前用户启用的光环厨师
            val enabledAuraChefs = getEnabledAuraChefs(gameData, personalData, settings, context)
            
            // 如果是光环厨师，添加光环信息
            if (result.isAuraChef && chef.name in enabledAuraChefs) {
                // 获取光环技能加成值和类型
                val (auraBonus, auraType) = getChefAuraBonusWithType(chef, gameData.skills, skillType)
                if (auraBonus > 0) {
                    // 根据光环类型决定乘数
                    val (multiplier, multiplierDesc) = when (auraType) {
                        "下位上场厨师" -> Pair(1, "X1")
                        "场上所有厨师" -> {
                            val peopleCount = settings.getLabAreaPeople(areaName)
                            Pair(peopleCount, "X$peopleCount")
                        }
                        else -> Pair(1, "X1")
                    }
                    val totalAuraBonus = auraBonus * multiplier
                    detailsBuilder.append("（光环：${skillType}+${auraBonus} ${multiplierDesc} = ${totalAuraBonus}）")
                }
            }
            
            val chefResult = ChefResult(
                name = result.chefName,
                rarity = result.rarity,
                timeSeconds = 0, // 实验室不使用时间效率
                owned = result.owned,
        area = areaName,
                collectionDetails = detailsBuilder.toString(),
                isUltimate = chef.ult
            )
            
            // 从可用厨师池中移除已使用的厨师
            availableChefs.removeAll { it.name == result.chefName }
            
            allResults.add(chefResult)
        }
    }
}

/**
 * 处理单个调料区地区的查询
 */
private fun processCondAreaSingle(
    areaName: String,
    gameData: GameData,
    availableChefs: MutableList<Chef>,
    personalData: PersonalData?,
    settings: com.example.show_auto.data.SettingsStorage,
    allResults: MutableList<ChefResult>
) {
    val people = settings.getCondAreaPeople(areaName)
    val capacity = settings.getCondAreaCapacity(areaName, 60)
    
    if (people <= 0) return
    

    
    // 调料区暂时显示功能开发中的占位结果
    val condResult = ChefResult(
        name = "调料区功能开发中",
        rarity = 1,
        timeSeconds = 0,
        owned = false,
        area = areaName,
        collectionDetails = "功能开发中，敬请期待",
        isUltimate = false
    )
    allResults.add(condResult)
}

/**
 * 计算厨师的原始采集点（包含厨师技能加成，但不包含厨具、心法盘等）
 */
private fun calculateChefBaseCollectionPoints(
    chef: Chef,
    gameData: GameData,
    personalData: PersonalData?
): Map<String, Int> {
    var meatBonus = 0
    var fishBonus = 0
    var vegBonus = 0
    var creationBonus = 0
    
    // 解析厨师自身技能（如果有的话）
    if (chef.skill != 0) {
        val skill = gameData.skills.find { it.skillId == chef.skill }
        if (skill != null) {
            val bonus = parseChefCollectionSkillBonus(skill.desc)
            meatBonus += bonus["肉"] ?: 0
            fishBonus += bonus["鱼"] ?: 0
            vegBonus += bonus["菜"] ?: 0
            creationBonus += bonus["面"] ?: 0
        }
    }
    
    // 解析厨师修炼技能
    if (chef.hasUltimateSkill()) {
        chef.getAllUltimateSkills().forEach { sid ->
            val skill = gameData.skills.find { it.skillId == sid }
            if (skill != null) {
                val bonus = parseChefCollectionSkillBonus(skill.desc)
                meatBonus += bonus["肉"] ?: 0
                fishBonus += bonus["鱼"] ?: 0
                vegBonus += bonus["菜"] ?: 0
                creationBonus += bonus["面"] ?: 0
            }
        }
    }
    
    return mapOf(
        "肉" to (chef.meat + meatBonus),
        "鱼" to (chef.fish + fishBonus),
        "菜" to (chef.veg + vegBonus),
        "面" to (chef.creation + creationBonus)
    )
}

/**
 * 解析厨师技能中的采集点加成
 */
private fun parseChefCollectionSkillBonus(skillDesc: String): Map<String, Int> {
    val bonus = mutableMapOf<String, Int>()
    
    // 解析各种采集加成格式
    // 肉类采集+数字
    val meatPattern = Regex("肉类采集\\+(\\d+)")
    meatPattern.find(skillDesc)?.let {
        bonus["肉"] = it.groupValues[1].toInt()
    }
    
    // 水产采集+数字（对应鱼类）
    val fishPattern = Regex("水产采集\\+(\\d+)")
    fishPattern.find(skillDesc)?.let {
        bonus["鱼"] = it.groupValues[1].toInt()
    }
    
    // 蔬菜采集+数字
    val vegPattern = Regex("蔬菜采集\\+(\\d+)")
    vegPattern.find(skillDesc)?.let {
        bonus["菜"] = it.groupValues[1].toInt()
    }
    
    // 面类采集+数字
    val creationPattern = Regex("面类采集\\+(\\d+)")
    creationPattern.find(skillDesc)?.let {
        bonus["面"] = it.groupValues[1].toInt()
    }
    
    return bonus
}

// 新的简化版区域配置Dialog
@Composable
private fun NewVegAreaConfigDialog(onDismiss: () -> Unit) {
    val context = LocalContext.current
    val settings = remember { SettingsStorage(context) }
    
    // 银布鞋开关状态
    var useSilverShoes by remember { mutableStateOf(settings.getUseSilverShoes()) }
    
    // 满级心法盘开关状态
    var useMaxLevelAmber by remember { mutableStateOf(settings.getUseMaxLevelAmber()) }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "菜地区配置",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 银布鞋开关
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFF5F5F5)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                Text(
                                text = "是否默认使用银布鞋",
                    fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = Color.Black
                            )
                            Text(
                                text = "开启后，厨师厨具效率低于银布鞋的都会替换为银布鞋查询",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                        
                        Switch(
                            checked = useSilverShoes,
                            onCheckedChange = { checked ->
                                useSilverShoes = checked
                                settings.saveUseSilverShoes(checked)
                            },
                            colors = SwitchDefaults.colors(
                                checkedThumbColor = MaterialTheme.colorScheme.primary,
                                checkedTrackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                            )
                        )
                    }
                }
                
                // 满级心法盘开关
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFF5F5F5)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                text = "是否默认满级心法盘",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = Color.Black
                            )
                            Text(
                                text = "开启后，默认使用满级素材加成心法盘",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                        
                        Switch(
                            checked = useMaxLevelAmber,
                            onCheckedChange = { checked ->
                                useMaxLevelAmber = checked
                                settings.saveUseMaxLevelAmber(checked)
                            },
                            colors = SwitchDefaults.colors(
                                checkedThumbColor = MaterialTheme.colorScheme.primary,
                                checkedTrackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                            )
                        )
                    }
                }
                
            }
        },
        confirmButton = {
            Button(onClick = onDismiss) {
                Text("确定")
            }
        }
    )
}

@Composable
private fun NewJadeAreaConfigDialog(onDismiss: () -> Unit) {
    val context = LocalContext.current
    val settings = remember { SettingsStorage(context) }
    
    // 玉片区银布鞋开关状态
    var useJadeSilverShoes by remember { mutableStateOf(settings.getUseJadeSilverShoes()) }
    
    // 玉片区满级心法盘开关状态
    var useJadeMaxLevelAmber by remember { mutableStateOf(settings.getUseJadeMaxLevelAmber()) }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "玉片区配置",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 银布鞋开关
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFF5F5F5)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                text = "是否默认使用银布鞋",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = Color.Black
                            )
                            Text(
                                text = "开启后，厨师厨具效率低于银布鞋的都会替换为银布鞋查询",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                        
                        Switch(
                            checked = useJadeSilverShoes,
                            onCheckedChange = { checked ->
                                useJadeSilverShoes = checked
                                settings.saveUseJadeSilverShoes(checked)
                            },
                            colors = SwitchDefaults.colors(
                                checkedThumbColor = MaterialTheme.colorScheme.primary,
                                checkedTrackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                            )
                        )
                    }
                }
                
                // 满级心法盘开关
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFF5F5F5)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                text = "是否默认满级心法盘",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = Color.Black
                            )
                            Text(
                                text = "开启后，默认使用满级采集点加成心法盘",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                        
                        Switch(
                            checked = useJadeMaxLevelAmber,
                            onCheckedChange = { checked ->
                                useJadeMaxLevelAmber = checked
                                settings.saveUseJadeMaxLevelAmber(checked)
                            },
                            colors = SwitchDefaults.colors(
                                checkedThumbColor = MaterialTheme.colorScheme.primary,
                                checkedTrackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                            )
                        )
                    }
                }
            }
        },
        confirmButton = {
            Button(onClick = onDismiss) {
                Text("确定")
            }
        }
    )
}

@Composable
private fun NewLabAreaConfigDialog(onDismiss: () -> Unit) {
    val context = LocalContext.current
    val settings = SettingsStorage(context)
    
    var useLabEquip150 by remember { mutableStateOf(settings.getUseLabEquip150()) }
    var useBeginnerEquip100 by remember { mutableStateOf(settings.getUseBeginnerEquip100()) }
    var useMaxLevelAmber by remember { mutableStateOf(settings.getUseMaxLevelAmber()) }
    var showResearchGuaranteeDialog by remember { mutableStateOf(false) }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "实验室配置",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
                Button(
                    onClick = { showResearchGuaranteeDialog = true },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.secondaryContainer,
                        contentColor = MaterialTheme.colorScheme.onSecondaryContainer
                    )
                ) {
                    Text(
                        text = "研发保底",
                        fontSize = 12.sp
                    )
                }
            }
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 默认使用实验室150厨具开关
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color.Transparent
                    ),
                    border = BorderStroke(1.dp, Color.Gray.copy(alpha = 0.3f))
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                Text(
                                text = "默认使用实验室150厨具",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                            Text(
                                text = "开启后，默认使用150技法厨具",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                        Switch(
                            checked = useLabEquip150,
                            onCheckedChange = { 
                                useLabEquip150 = it
                                // 自动保存设置
                                settings.saveUseLabEquip150(it)
                                // 如果开启实验室150厨具，则关闭新手100厨具
                                if (it) {
                                    useBeginnerEquip100 = false
                                    settings.saveUseBeginnerEquip100(false)
                                }
                            }
                        )
                    }
                }
                
                // 默认使用新手100厨具开关
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color.Transparent
                    ),
                    border = BorderStroke(1.dp, Color.Gray.copy(alpha = 0.3f))
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                text = "默认使用新手100厨具",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                            Text(
                                text = "开启后，默认使用100技法厨具",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                        Switch(
                            checked = useBeginnerEquip100,
                            onCheckedChange = { 
                                useBeginnerEquip100 = it
                                // 自动保存设置
                                settings.saveUseBeginnerEquip100(it)
                                // 如果开启新手100厨具，则关闭实验室150厨具
                                if (it) {
                                    useLabEquip150 = false
                                    settings.saveUseLabEquip150(false)
                                }
                            }
                        )
                    }
                }
                
                // 默认使用满级心法盘开关
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color.Transparent
                    ),
                    border = BorderStroke(1.dp, Color.Gray.copy(alpha = 0.3f))
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                text = "默认使用满级心法盘",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                            Text(
                                text = "开启后，默认满级心法盘",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                        Switch(
                            checked = useMaxLevelAmber,
                            onCheckedChange = { 
                                useMaxLevelAmber = it
                                // 自动保存设置
                                settings.saveUseMaxLevelAmber(it)
                            }
                        )
                    }
                }
            }
        },
        confirmButton = {
            Button(onClick = onDismiss) {
                Text("确定")
            }
        }
    )
    
    // 研发保底技法值弹窗
    if (showResearchGuaranteeDialog) {
        ResearchGuaranteeDialog(
            onDismiss = { showResearchGuaranteeDialog = false }
        )
    }
}

@Composable
private fun NewCondAreaConfigDialog(onDismiss: () -> Unit) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "调料区配置",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "调料区配置页面正在开发中...",
                    fontSize = 16.sp,
                    color = Color.Gray
                )
            }
        },
        confirmButton = {
            Button(onClick = onDismiss) {
                Text("确定")
            }
        }
    )
}

/**
 * 厨师选择弹窗
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ChefSelectionDialog(
    onDismiss: () -> Unit,
    onSelectionChanged: (Set<String>) -> Unit = {}
) {
    val context = LocalContext.current
    val viewModel: MainViewModel = viewModel()
    val gameData by viewModel.gameData.collectAsState()
    val personalData by viewModel.personalData.collectAsState()
    val settings = SettingsStorage(context)
    
    // 获取所有厨师列表
    val allChefs = gameData?.chefs ?: emptyList()
    
    // 使用全部厨师开关状态 - 从设置中读取初始值
    var useAllChefs by remember { mutableStateOf(settings.getCalculatorUseAllChefs()) }
    
    // 默认全修炼开关状态
    var useAllUltimateTraining by remember { mutableStateOf(settings.getUseAllUltimateTraining()) }
    
    // 厨师选择状态 - 从设置中读取已保存的选择，如果没有则默认选择已拥有的厨师
    var selectedChefs by remember { 
        mutableStateOf(
            run {
                // 首先尝试从设置中读取已保存的选择
                val savedChefNames = settings.getSelectedQueryChefs()
                if (savedChefNames.isNotEmpty()) {
                    // 将厨师名称转换为厨师ID
                    val savedChefIds = allChefs.filter { chef ->
                        chef.name in savedChefNames
                    }.map { it.chefId }.toSet()
                    println("DEBUG: 厨师选择对话框 - 从设置读取已保存选择: ${savedChefIds.size} 个厨师")
                    savedChefIds
                } else {
                    // 如果没有保存的选择，默认选择已拥有的厨师
                    val currentPersonalData = personalData
                    if (currentPersonalData != null) {
                        val ownedChefIds = allChefs.filter { chef ->
                            currentPersonalData.chefs[chef.chefId]?.got == true
                        }.map { it.chefId }.toSet()
                        println("DEBUG: 厨师选择对话框 - 初始化已拥有厨师数量: ${ownedChefIds.size}")
                        ownedChefIds
                    } else {
                        println("DEBUG: 厨师选择对话框 - 无个人数据，初始化为空")
                        emptySet()
                    }
                }
            }
        )
    }
    
    // 搜索关键词
    var searchText by remember { mutableStateOf("") }
    
    // 筛选类型状态
    var selectedFilterTypes by remember { mutableStateOf(setOf<String>()) }
    var showFilterDropdown by remember { mutableStateOf(false) }
    
    // 厨师分类切换状态：true=采集厨师，false=普通厨师
    var showCollectionChefs by remember { mutableStateOf(true) }
    
    // 初始化完成后通知父组件
    LaunchedEffect(selectedChefs) {
        onSelectionChanged(selectedChefs)
    }
    
    // 判断厨师是否为采集厨师（按照一键查询逻辑）
    fun isCollectionChef(chef: Chef): Boolean {
        if (gameData == null) return false
        val skillBonus = CollectionTeamCalculator.calculateSeparatedSkillBonus(chef, gameData!!, personalData, "", false, settings.getUseMaxLevelAmber(), false, settings.getUseAllUltimateTraining())
        return skillBonus.totalCritMaterial > 0 || skillBonus.totalMaterialGain > 0
    }
    
    // 根据开关状态筛选厨师列表
    val availableChefs = remember(allChefs, useAllChefs, personalData) {
        if (useAllChefs) {
            allChefs
        } else {
            // 只显示已拥有的厨师
            val currentPersonalData = personalData
            if (currentPersonalData != null) {
                allChefs.filter { chef ->
                    currentPersonalData.chefs[chef.chefId]?.got == true
                }
            } else {
                emptyList()
            }
        }
    }
    
    // 分类厨师列表
    val (collectionChefs, normalChefs) = remember(availableChefs, gameData, personalData) {
        val collection = mutableListOf<Chef>()
        val normal = mutableListOf<Chef>()
        
        availableChefs.forEach { chef ->
            if (isCollectionChef(chef)) {
                collection.add(chef)
            } else {
                normal.add(chef)
            }
        }
        
        Pair(collection, normal)
    }
    
    // 过滤后的厨师列表（根据分类、搜索条件和类型筛选，按采集期望值降序排序）
    val filteredChefs = remember(collectionChefs, normalChefs, searchText, showCollectionChefs, selectedFilterTypes, gameData, personalData) {
        val sourceList = if (showCollectionChefs) collectionChefs else normalChefs
        val filtered = sourceList.filter { chef ->
            // 名称筛选
            val nameMatch = searchText.isEmpty() || chef.name.contains(searchText, ignoreCase = true)
            
            // 类型筛选
            val typeMatch = if (selectedFilterTypes.isEmpty()) {
                true
            } else {
                // 检查厨师是否同时拥有所有选择的采集类型
                selectedFilterTypes.all { filterType ->
                    when (filterType) {
                        "鱼" -> chef.fish > 0
                        "肉" -> chef.meat > 0
                        "菜" -> chef.veg > 0
                        "面" -> chef.creation > 0
                        else -> true
                    }
                }
            }
            
            nameMatch && typeMatch
        }
        
        // 根据厨师分类应用不同的排序逻辑
        if (showCollectionChefs && gameData != null) {
            // 采集厨师按采集期望值降序排序
            filtered.sortedByDescending { chef ->
                val skillBonus = CollectionTeamCalculator.calculateSeparatedSkillBonus(chef, gameData!!, personalData, "", false, settings.getUseMaxLevelAmber(), false, settings.getUseAllUltimateTraining())
                skillBonus.totalMaterialGain + (skillBonus.totalCritChance / 100.0 * skillBonus.totalCritMaterial)
            }
        } else {
            // 普通厨师排序逻辑
            if (selectedFilterTypes.isNotEmpty()) {
                // 有筛选类型时，仅按选择类型的采集点综合降序排序
                filtered.sortedByDescending { chef ->
                    selectedFilterTypes.sumOf { filterType ->
                        when (filterType) {
                            "鱼" -> chef.fish
                            "肉" -> chef.meat
                            "菜" -> chef.veg
                            "面" -> chef.creation
                            else -> 0
                        }
                    }
                }
            } else {
                // 无筛选类型时，按星级降序，同星级按厨师ID降序排序
                filtered.sortedWith(compareByDescending<Chef> { it.rarity }.thenByDescending { it.chefId.toIntOrNull() ?: 0 })
            }
        }
    }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        properties = WindowDialogProperties(usePlatformDefaultWidth = false),
        title = { 
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(6.dp)
                ) {
                    Text(
                        text = "使用全部厨师",
                        fontSize = 12.sp,
                        color = Color(0xFF666666)
                    )
                    Switch(
                        checked = useAllChefs,
                        onCheckedChange = { 
                            useAllChefs = it
                            settings.saveCalculatorUseAllChefs(it) // 保存到设置
                        },
                        modifier = Modifier.scale(0.7f)
                    )
                }
                
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(6.dp)
                ) {
                    Text(
                        text = "默认全修炼",
                        fontSize = 12.sp,
                        color = Color(0xFF666666)
                    )
                    Switch(
                        checked = useAllUltimateTraining,
                        onCheckedChange = { 
                            useAllUltimateTraining = it
                            settings.saveUseAllUltimateTraining(it)
                        },
                        modifier = Modifier.scale(0.7f)
                    )
                }
            }
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(600.dp)
            ) {
                // 搜索框和筛选框行
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 搜索框
                OutlinedTextField(
                    value = searchText,
                    onValueChange = { searchText = it },
                        placeholder = { Text("搜索厨师") },
                        modifier = Modifier.weight(1f),
                    leadingIcon = {
                        Icon(Icons.Default.Search, contentDescription = "搜索")
                    },
                    trailingIcon = {
                        if (searchText.isNotEmpty()) {
                            IconButton(onClick = { searchText = "" }) {
                                Icon(Icons.Default.Clear, contentDescription = "清除")
                            }
                        }
                        },
                        singleLine = true
                )
                    
                    // 筛选类型下拉框
                    Box(modifier = Modifier.width(120.dp)) {
                        OutlinedTextField(
                            value = when {
                                selectedFilterTypes.isEmpty() -> "全部"
                                selectedFilterTypes.size == 1 -> selectedFilterTypes.first()
                                else -> selectedFilterTypes.joinToString(",")
                            },
                            onValueChange = { },
                            readOnly = true,
                            placeholder = { Text("筛选类型") },
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { showFilterDropdown = true },
                            trailingIcon = {
                                IconButton(onClick = { showFilterDropdown = true }) {
                                    Icon(
                                        imageVector = if (showFilterDropdown) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                        contentDescription = null
                                    )
                                }
                            },
                            singleLine = true
                        )
                        
                        DropdownMenu(
                            expanded = showFilterDropdown,
                            onDismissRequest = { showFilterDropdown = false },
                            modifier = Modifier.width(120.dp)
                        ) {
                            val filterOptions = listOf("全部", "鱼", "肉", "菜", "面")
                            
                            filterOptions.forEach { option ->
                                val isSelected = if (option == "全部") {
                                    selectedFilterTypes.isEmpty()
                                } else {
                                    selectedFilterTypes.contains(option)
                                }
                                
                                DropdownMenuItem(
                                    text = {
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .background(
                                                    color = if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.1f) else Color.Transparent,
                                                    shape = RoundedCornerShape(4.dp)
                                                )
                                                .padding(vertical = 2.dp),
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Text(
                                                text = option,
                                                fontSize = 14.sp,
                                                color = if (isSelected) {
                                                    MaterialTheme.colorScheme.primary
                                                } else {
                                                    MaterialTheme.colorScheme.onSurface
                                                },
                                                fontWeight = if (isSelected) FontWeight.Medium else FontWeight.Normal
                                            )
                                        }
                                    },
                                    onClick = {
                                        if (option == "全部") {
                                            selectedFilterTypes = emptySet()
                                            showFilterDropdown = false
                                        } else {
                                            selectedFilterTypes = if (selectedFilterTypes.contains(option)) {
                                                selectedFilterTypes - option
                                            } else {
                                                selectedFilterTypes + option
                                            }
                                        }
                                    },
                                    modifier = Modifier.height(32.dp)
                                )
                            }
                        }
                    }
                }
                
                // 操作按钮行
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Button(
                        onClick = {
                            // 全选当前分类中的厨师
                            val targetChefs = if (showCollectionChefs) collectionChefs else normalChefs
                            selectedChefs = selectedChefs + targetChefs.map { it.chefId }.toSet()
                            // 实时保存厨师选择状态
                            val selectedChefNames = allChefs.filter { it.chefId in selectedChefs }.map { it.name }.toSet()
                            settings.saveSelectedQueryChefs(selectedChefNames)
                                
                                // 通知父组件状态变化
                                onSelectionChanged(selectedChefs)
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary
                        ),
                        contentPadding = PaddingValues(0.dp)
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                    ) {
                        Text("全选", fontSize = 12.sp)
                        }
                    }
                    
                    Button(
                        onClick = {
                            // 取消全选当前分类中的厨师
                            val targetChefs = if (showCollectionChefs) collectionChefs else normalChefs
                            selectedChefs = selectedChefs - targetChefs.map { it.chefId }.toSet()
                            // 实时保存厨师选择状态
                            val selectedChefNames = allChefs.filter { it.chefId in selectedChefs }.map { it.name }.toSet()
                            settings.saveSelectedQueryChefs(selectedChefNames)
                                
                                // 通知父组件状态变化
                                onSelectionChanged(selectedChefs)
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.secondary
                        ),
                        contentPadding = PaddingValues(0.dp)
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                    ) {
                            Text("取消全选", fontSize = 12.sp)
                        }
                    }
                }
                
                // 厨师分类切换框 - 胶囊式切换（与查询结果地区切换一致）
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp),
                    shape = RoundedCornerShape(20.dp),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFE3F2FD)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Row(modifier = Modifier.padding(4.dp)) {
                        // 采集厨师按钮
                        Surface(
                            onClick = { showCollectionChefs = true },
                            modifier = Modifier
                                .weight(1f)
                                .height(28.dp),
                            shape = RoundedCornerShape(16.dp),
                            color = if (showCollectionChefs) MaterialTheme.colorScheme.primary else Color.Transparent
                        ) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = "采集厨师 (${collectionChefs.size})",
                                    fontSize = 12.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = if (showCollectionChefs) Color.White else MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                        
                        Spacer(modifier = Modifier.width(4.dp))
                        
                        // 普通厨师按钮
                        Surface(
                            onClick = { showCollectionChefs = false },
                            modifier = Modifier
                                .weight(1f)
                                .height(28.dp),
                            shape = RoundedCornerShape(16.dp),
                            color = if (!showCollectionChefs) MaterialTheme.colorScheme.primary else Color.Transparent
                        ) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = "普通厨师 (${normalChefs.size})",
                                    fontSize = 12.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = if (!showCollectionChefs) Color.White else MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                    }
                }
                

                
                // 厨师列表
                LazyColumn {
                    items(filteredChefs) { chef ->
                        val isSelected = selectedChefs.contains(chef.chefId)
                        val isOwned = personalData?.chefs?.get(chef.chefId)?.got == true
                        
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp)
                                                            .clickable {
                                selectedChefs = if (isSelected) {
                                    selectedChefs - chef.chefId
                                } else {
                                    selectedChefs + chef.chefId
                                }
                                // 实时保存厨师选择状态
                                val selectedChefNames = allChefs.filter { it.chefId in selectedChefs }.map { it.name }.toSet()
                                settings.saveSelectedQueryChefs(selectedChefNames)
                            },
                            colors = CardDefaults.cardColors(
                                containerColor = if (isSelected) {
                                    MaterialTheme.colorScheme.primaryContainer
                                } else {
                                    MaterialTheme.colorScheme.surface
                                }
                            ),
                            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(12.dp)
                            ) {
                                // 厨师信息
                                Column(modifier = Modifier.fillMaxWidth()) {
                                    // 第一行：厨师名称 + 星级 + 绿色心法盘数量 + 厨师来源
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Text(
                                            text = chef.name,
                                            fontSize = 14.sp,
                                            fontWeight = FontWeight.Medium,
                                            color = if (isOwned) {
                                                MaterialTheme.colorScheme.onSurface
                                            } else {
                                                Color.Gray
                                            }
                                        )
                                        
                                        Spacer(modifier = Modifier.width(4.dp))
                                        
                                        // 星级显示（参考查询结果厨师卡片颜色）
                                        repeat(chef.rarity) {
                                            Text(
                                                text = "★",
                                                color = Color(0xFF2196F3), // 蓝色
                                                fontSize = 12.sp
                                            )
                                        }
                                        
                                        // 显示绿色心法盘数量
                                        if (gameData != null) {
                                            val greenAmberCount = extractGreenAmberCount(chef.diskDesc)
                                            val displayText = if (greenAmberCount > 0) {
                                                "绿色心法盘X$greenAmberCount"
                                            } else {
                                                "无绿色心法盘"
                                            }
                                            Spacer(modifier = Modifier.width(4.dp))
                                            Text(
                                                text = displayText,
                                                fontSize = 10.sp,
                                                fontWeight = FontWeight.Normal,
                                                color = Color(0xFF4CAF50) // 绿色
                                            )
                                        }
                                        
                                        Spacer(modifier = Modifier.weight(1f))
                                        
                                        // 厨师来源
                                        if (chef.origin.isNotEmpty()) {
                                            Text(
                                                text = "来源：${chef.origin.replace("<br>", "\n")}",
                                                fontSize = 8.sp,
                                                color = Color.Gray,
                                                fontStyle = FontStyle.Italic
                                            )
                                        }
                                    }
                                    
                                    Spacer(modifier = Modifier.height(2.dp))
                                    
                                    // 第二行：采集点信息 + 采集期望值 + 选择框
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.SpaceBetween
                                    ) {
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            modifier = Modifier.weight(1f)
                                        ) {
                                            // 计算包含厨具和心法盘加成的采集点（参考查询结果厨师卡片）
                                            val collectionStats = if (gameData != null) {
                                                CollectionTeamCalculator.calculateChefCollectionStats(chef, gameData!!, personalData, false, settings.getUseMaxLevelAmber(), "", false, settings.getUseAllUltimateTraining())
                                            } else {
                                                CollectionTeamCalculator.CollectionStats(
                                                    meat = chef.meat,
                                                    fish = chef.fish,
                                                    veg = chef.veg,
                                                    creation = chef.creation
                                                )
                                            }
                                            
                                            Text(
                                                text = "肉:${collectionStats.meat} 鱼:${collectionStats.fish} 菜:${collectionStats.veg} 面:${collectionStats.creation}",
                                                fontSize = 11.sp,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant
                                            )
                                            
                                            // 采集期望值（仅对采集厨师显示）
                                            if (showCollectionChefs && isCollectionChef(chef)) {
                                                val skillBonus = if (gameData != null) {
                                                    CollectionTeamCalculator.calculateSeparatedSkillBonus(chef, gameData!!, personalData, "", false, settings.getUseMaxLevelAmber(), false, settings.getUseAllUltimateTraining())
                                                } else {
                                                    CollectionTeamCalculator.SeparatedSkillBonus()
                                                }
                                                val expectationValue = skillBonus.totalMaterialGain + (skillBonus.totalCritChance / 100.0 * skillBonus.totalCritMaterial)
                                                if (expectationValue > 0) {
                                                    Spacer(modifier = Modifier.width(8.dp))
                                                    Text(
                                                        text = "采集期望值：${String.format("%.0f", expectationValue)}",
                                                        fontSize = 10.sp,
                                                        color = Color(0xFF9C27B0), // 紫色
                                                        fontWeight = FontWeight.Medium
                                                    )
                                                }
                                            }
                                        }
                                        
                                        // 选择框
                                        Checkbox(
                                            checked = isSelected,
                                            onCheckedChange = { checked ->
                                                selectedChefs = if (checked) {
                                                    selectedChefs + chef.chefId
                                                } else {
                                                    selectedChefs - chef.chefId
                                                }
                                                // 实时保存厨师选择状态
                                                val selectedChefNames = allChefs.filter { it.chefId in selectedChefs }.map { it.name }.toSet()
                                                settings.saveSelectedQueryChefs(selectedChefNames)
                                                println("DEBUG: 厨师选择 - 保存厨师选择: ${selectedChefNames.joinToString(", ")}")
                                                
                                                // 通知父组件状态变化
                                                onSelectionChanged(selectedChefs)
                                            }
                                        )
                                    }
                                    
                                    // 第三行：技能详情 + 修炼状态 + 拥有状态（仅对采集厨师显示）
                                    if (showCollectionChefs && isCollectionChef(chef)) {
                                        Spacer(modifier = Modifier.height(2.dp))
                                        
                                        val skillBonus = if (gameData != null) {
                                            CollectionTeamCalculator.calculateSeparatedSkillBonus(chef, gameData!!, personalData, "", false, settings.getUseMaxLevelAmber(), false, settings.getUseAllUltimateTraining())
                                        } else {
                                            CollectionTeamCalculator.SeparatedSkillBonus()
                                        }
                                        
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            // 左侧：技能详情
                                            Row(
                                                horizontalArrangement = Arrangement.spacedBy(8.dp),
                                                verticalAlignment = Alignment.CenterVertically
                                            ) {
                                                // 素材加成
                                                Text(
                                                    text = "素材:${skillBonus.totalMaterialGain}%",
                                                    fontSize = 10.sp,
                                                    color = if (skillBonus.totalMaterialGain > 0) Color(0xFF7B1FA2) else MaterialTheme.colorScheme.onSurfaceVariant,
                                                    fontWeight = if (skillBonus.totalMaterialGain > 0) FontWeight.Medium else FontWeight.Normal
                                                )
                                                
                                                // 暴击素材
                                                Text(
                                                    text = "暴击素材:${skillBonus.totalCritMaterial}%",
                                                    fontSize = 10.sp,
                                                    color = if (skillBonus.totalCritMaterial > 0) Color(0xFF1565C0) else MaterialTheme.colorScheme.onSurfaceVariant,
                                                    fontWeight = if (skillBonus.totalCritMaterial > 0) FontWeight.Medium else FontWeight.Normal
                                                )
                                                
                                                // 暴击率
                                                Text(
                                                    text = "暴击率:${skillBonus.totalCritChance}%",
                                                    fontSize = 10.sp,
                                                    color = if (skillBonus.totalCritChance > 0) Color(0xFFFF5722) else MaterialTheme.colorScheme.onSurfaceVariant,
                                                    fontWeight = if (skillBonus.totalCritChance > 0) FontWeight.Medium else FontWeight.Normal
                                                )
                                            }
                                            
                                            // 右侧：修炼和拥有状态
                                            Row(
                                                horizontalArrangement = Arrangement.spacedBy(4.dp),
                                                verticalAlignment = Alignment.CenterVertically
                                            ) {
                                                // 修炼状态
                                                Text(
                                                    text = if (chef.ult) "已修炼" else "未修炼",
                                                    fontSize = 10.sp,
                                                    color = if (chef.ult) MaterialTheme.colorScheme.primary else Color.Gray,
                                                    fontWeight = if (chef.ult) FontWeight.Medium else FontWeight.Normal
                                                )
                                                
                                                // 拥有状态
                                                if (!isOwned) {
                                                    Text(
                                                        text = "未拥有",
                                                        fontSize = 10.sp,
                                                        color = Color.Red
                                                    )
                                                }
                                            }
                                        }
                                    } else if (!showCollectionChefs) {
                                        // 普通厨师只显示修炼和拥有状态
                                        Spacer(modifier = Modifier.height(2.dp))
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.End,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            // 修炼状态
                                            Text(
                                                text = if (chef.ult) "已修炼" else "未修炼",
                                                fontSize = 10.sp,
                                                color = if (chef.ult) MaterialTheme.colorScheme.primary else Color.Gray,
                                                fontWeight = if (chef.ult) FontWeight.Medium else FontWeight.Normal
                                            )
                                            
                                            // 拥有状态
                                            if (!isOwned) {
                                                Spacer(modifier = Modifier.width(4.dp))
                                                Text(
                                                    text = "未拥有",
                                                    fontSize = 10.sp,
                                                    color = Color.Red
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(
                onClick = {
                    // TODO: 保存选择的厨师到设置中
                    onDismiss()
                }
            ) { 
                Text("确定") 
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) { 
                Text("取消") 
            }
        }
    )
}



// 获取实验室区域配置
private fun getLabAreaConfigs(settings: com.example.show_auto.data.SettingsStorage): List<CollectionTeamCalculator.LabAreaItem> {
    // 默认实验室配置
    val defaultItems = listOf(
        CollectionTeamCalculator.LabAreaItem("蒸", 5),
        CollectionTeamCalculator.LabAreaItem("炸", 5),
        CollectionTeamCalculator.LabAreaItem("炒", 5),
        CollectionTeamCalculator.LabAreaItem("煮", 5),
        CollectionTeamCalculator.LabAreaItem("切", 5),
        CollectionTeamCalculator.LabAreaItem("烤", 5)
    )
    
    // 加载已保存顺序，按顺序重新排列
    val savedOrder = settings.getLabAreaOrder()
    
    return if (savedOrder.isEmpty()) {
        // 如果没有保存的顺序，使用默认顺序
        defaultItems.map { item ->
            val savedPeople = settings.getLabAreaPeople(item.name)
            item.copy(currentPeople = savedPeople)
        }
    } else {
        // 按保存的顺序重新排列，保留原有数据并加载保存的配置
        savedOrder.mapNotNull { savedName ->
            defaultItems.find { it.name == savedName }?.let { item ->
                val savedPeople = settings.getLabAreaPeople(item.name)
                item.copy(currentPeople = savedPeople)
            }
        } + defaultItems.filter { item ->
            item.name !in savedOrder
        }.map { item ->
            val savedPeople = settings.getLabAreaPeople(item.name)
            item.copy(currentPeople = savedPeople)
        }
    }
}

/**
 * 获取厨师的光环加成值
 */
private fun getChefAuraBonus(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>, skillType: String): Int {
    return getChefAuraBonusWithType(chef, skills, skillType).first
}

/**
 * 获取厨师的光环加成值和光环类型
 * @return Pair<加成值, 光环类型>
 */
private fun getChefAuraBonusWithType(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>, skillType: String): Pair<Int, String> {
    // 获取所有修炼技能的描述
    val skillDescs = chef.getAllUltimateSkills().mapNotNull { skillId ->
        skills.find { it.skillId == skillId }?.desc
    }
    val combinedDesc = skillDescs.joinToString("\n")
    
    // 检查是否为光环厨师
    val isAuraChef = (combinedDesc.contains("场上所有厨师") || combinedDesc.contains("下位上场厨师")) &&
                    !combinedDesc.contains("采集") &&
                    !combinedDesc.contains("菜") &&
                    !combinedDesc.contains("鱼") &&
                    !combinedDesc.contains("肉") &&
                    !combinedDesc.contains("面")
    
    if (!isAuraChef) return Pair(0, "")
    
    // 查找对应技法的加成值和类型
    chef.getAllUltimateSkills().forEach { skillId ->
        val skill = skills.find { it.skillId == skillId }
        if (skill != null) {
            val desc = skill.desc
            
            // 检查是否匹配当前技法类型
            if (desc.contains("${skillType}+") || desc.contains("${skillType}技法") || desc.contains("全技法+")) {
                val bonus = extractBonusAmount(desc)
                if (bonus > 0) {
                    // 确定光环类型
                    val auraType = when {
                        desc.contains("场上所有厨师") -> "场上所有厨师"
                        desc.contains("下位上场厨师") -> "下位上场厨师"
                        else -> "未知"
                    }
                    return Pair(bonus, auraType)
                }
            }
        }
    }
    
    return Pair(0, "")
}

/**
 * 从技能描述中提取加成数值
 */
private fun extractBonusAmount(desc: String): Int {
    // 查找 "技法+数字" 或 "类型+数字" 格式
    val regex = Regex("[+](\\d+)")
    val match = regex.find(desc)
    return match?.groupValues?.get(1)?.toIntOrNull() ?: 0
}

/**
 * 获取厨师的技能描述
 */
private fun getChefSkillDescription(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): String {
    if (!chef.hasUltimateSkill()) return ""
    val descs = chef.getAllUltimateSkills().mapNotNull { sid ->
        skills.find { it.skillId == sid }?.desc
    }
    return descs.joinToString("\n")
}

/**
 * 统一的光环厨师筛选逻辑
 * 基于技能effect字段进行精确判断
 */
private fun isAuraChef(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    // 获取厨师的所有修炼技能
    val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
        skills.find { it.skillId == skillId }
    }
    
    // 检查是否有符合条件的光环技能
    return ultimateSkills.any { skill ->
        skill.effect?.any { effect ->
            // 条件1：condition必须是"Partial"或"Next"
            val conditionMatch = effect.condition == "Partial" || effect.condition == "Next"
            
            // 条件2：type必须是技法类型
            val typeMatch = effect.type in listOf("Bake", "Steam", "Boil", "Fry", "Knife", "Stirfry")
            
            // 条件3：value必须大于0
            val valueMatch = (effect.value ?: 0) > 0
            
            conditionMatch && typeMatch && valueMatch
        } ?: false
    }
}



/**
 * 获取当前启用的光环厨师
 * 返回游戏数据中所有符合条件的光环厨师
 */
private fun getEnabledAuraChefs(
    gameData: GameData,
    personalData: PersonalData?,
    settings: com.example.show_auto.data.SettingsStorage,
    context: android.content.Context?
): Set<String> {
    // 检查开关状态
    val useAllChefs = settings.getCalculatorUseAllChefs()
    val useAllUltimateTraining = settings.getUseAllUltimateTraining()
    
    // 实时识别光环厨师
    val allAuraChefs = gameData.chefs.filter { chef ->
        isAuraChef(chef, gameData.skills)
    }
    
    val enabledAuraChefs = if (useAllChefs) {
        if (useAllUltimateTraining) {
            // 使用全部厨师 + 默认全修炼：使用所有光环厨师（包括未拥有的）
            allAuraChefs.map { it.name }.toSet()
        } else {
            // 使用全部厨师 + 关闭默认全修炼：只使用已拥有且已修炼的光环厨师
            allAuraChefs.filter { chef ->
                val personalChef = personalData?.chefs?.get(chef.chefId)
                personalChef?.got == true && personalChef.ult == true
            }.map { it.name }.toSet()
        }
    } else {
        if (useAllUltimateTraining) {
            // 只用已拥有厨师 + 默认全修炼：使用已拥有的光环厨师（不需要检查修炼状态）
            allAuraChefs.filter { chef ->
                personalData?.chefs?.get(chef.chefId)?.got == true
            }.map { it.name }.toSet()
        } else {
            // 只用已拥有厨师 + 关闭默认全修炼：只使用已拥有且已修炼的光环厨师
            allAuraChefs.filter { chef ->
                val personalChef = personalData?.chefs?.get(chef.chefId)
                personalChef?.got == true && personalChef.ult == true
            }.map { it.name }.toSet()
        }
    }
    
    println("DEBUG: 实验室查询 - 使用全部厨师: $useAllChefs, 默认全修炼: $useAllUltimateTraining")
    println("DEBUG: 实验室查询 - 光环厨师总数: ${allAuraChefs.size}, 启用数量: ${enabledAuraChefs.size}")
    if (enabledAuraChefs.isNotEmpty()) {
        println("DEBUG: 启用的光环厨师: ${enabledAuraChefs.joinToString(", ")}")
    }
    
    return enabledAuraChefs
}

/**
 * 重新计算实验室区域的总技法值
 * 当替换厨师后，需要重新计算该实验室地区的总技法值
 */
private fun recalculateLabAreaTotalSkill(
    currentResults: List<ChefResult>,
    areaName: String,
    gameData: GameData,
    personalData: PersonalData?,
    settings: SettingsStorage,
    context: android.content.Context?
): List<ChefResult> {
    // 获取该实验室地区的所有厨师
    val labChefs = currentResults.filter { it.area == areaName }
    
    if (labChefs.isEmpty()) return currentResults
    
    // 重新计算该实验室地区的总技法值
    try {
        // 计算所有厨师的技法值总和
        var totalSkillValue = 0
        val skillType = areaName // 技法类型就是地区名
        
        // 获取启用的光环厨师
        val enabledAuraChefs = getEnabledAuraChefs(gameData, personalData, settings, context)
        
        labChefs.forEach { chefResult ->
            val chef = gameData.chefs.find { it.name == chefResult.name }
            if (chef != null) {
                // 计算该厨师的技法值
                val skillStats = CollectionTeamCalculator.calculateChefSkillStats(
                    chef = chef,
                    gameData = gameData,
                    personalData = personalData,
                    useLabEquip150 = settings.getUseLabEquip150(),
                    useBeginnerEquip100 = settings.getUseBeginnerEquip100(),
                    useMaxLevelAmber = settings.getUseMaxLevelAmber(),
                    context = context,
                    useAllUltimateTraining = settings.getUseAllUltimateTraining(),
                    targetSkillType = skillType
                )
                
                val skillValue = skillStats.getSkillValue(skillType)
                totalSkillValue += skillValue
            }
        }
        
                 // 计算光环厨师的额外加成
         enabledAuraChefs.forEach { auraChefName ->
             val auraChef = gameData.chefs.find { it.name == auraChefName }
             if (auraChef != null && auraChefName in labChefs.map { it.name }) {
                 val auraBonusResult = getChefAuraBonusWithType(auraChef, gameData.skills, skillType)
                 val auraBonus = auraBonusResult.first
                 val auraType = auraBonusResult.second
                 if (auraBonus > 0) {
                     val multiplier = when (auraType) {
                         "下位上场厨师" -> 1
                         "场上所有厨师" -> 5 // 实验室固定5人
                         else -> 1
                     }
                     totalSkillValue += auraBonus * multiplier
                 }
             }
         }
        
        // 更新计算器中的总技法值缓存
        CollectionTeamCalculator.updateLabAreaTotalSkill(skillType, totalSkillValue)
        
        println("实验室区域 $areaName 总技法值重新计算完成: $totalSkillValue")
        
    } catch (e: Exception) {
        println("重新计算实验室总技法值时发生错误: ${e.message}")
    }
    
    return currentResults
}

@Composable
private fun ResearchGuaranteeDialog(onDismiss: () -> Unit) {
    var selectedTab by remember { mutableStateOf(0) }
    val tabs = listOf("菜谱", "厨具")
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                verticalAlignment = Alignment.Bottom
            ) {
                Text(
                    text = "研发保底技法值",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = "（数据由梨大只提供～）",
                    fontSize = 12.sp,
                    color = Color.Gray,
                    modifier = Modifier.padding(start = 4.dp)
                )
            }
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(500.dp)
            ) {
                // Tab 选择器 - 圆角按钮样式
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(
                            Color.Gray.copy(alpha = 0.2f),
                            RoundedCornerShape(20.dp)
                        )
                        .padding(3.dp),
                    horizontalArrangement = Arrangement.spacedBy(3.dp)
                ) {
                    tabs.forEachIndexed { index, title ->
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .background(
                                    if (selectedTab == index) 
                                        MaterialTheme.colorScheme.primary
                                    else 
                                        Color.Transparent,
                                    RoundedCornerShape(16.dp)
                                )
                                .clickable { selectedTab = index }
                                .padding(vertical = 6.dp, horizontal = 12.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = title,
                                fontSize = 12.sp,
                                color = if (selectedTab == index) 
                                    Color.White 
                                else 
                                    MaterialTheme.colorScheme.onSurface,
                                fontWeight = if (selectedTab == index) 
                                    FontWeight.Bold 
                                else 
                                    FontWeight.Normal
                            )
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // Tab 内容
                when (selectedTab) {
                    0 -> RecipeResearchGuaranteeContent()
                    1 -> EquipResearchGuaranteeContent()
                }
            }
        },
        confirmButton = {
            Button(onClick = onDismiss) {
                Text("确定")
            }
        }
    )
}

@Composable
private fun RecipeResearchGuaranteeContent() {
    // 菜谱研发保底数据 - 分离技法值和锅数
    val researchData = listOf(
        ResearchGuaranteeItem("累计必定成功", "25000", "", "13333", "", "10000", "", "7500", "", "2500", ""),
        ResearchGuaranteeItem("一定成功", "12500", "", "6666", "", "5000", "", "3500", "", "2500", ""),
        ResearchGuaranteeItem("基本稳了", "11250", "(3锅)", "5999.4", "(3锅)", "4500", "(3锅)", "3150", "(3锅)", "2250", "(2锅)"),
        ResearchGuaranteeItem("希望很大", "10000", "(3锅)", "5332.8", "(3锅)", "4000", "(3锅)", "2800", "(3锅)", "2000", "(2锅)"),
        ResearchGuaranteeItem("好像很稳", "8750", "(3锅)", "4666.2", "(3锅)", "3500", "(3锅)", "2450", "(4锅)", "1750", "(2锅)"),
        ResearchGuaranteeItem("勉强及格", "7500", "(4锅)", "3999.6", "(4锅)", "3000", "(4锅)", "2100", "(4锅)", "1500", "(2锅)"),
        ResearchGuaranteeItem("成功过半", "6250", "(4锅)", "3333", "(5锅)", "2500", "(4锅)", "1750", "(5锅)", "1250", "(2锅)"),
        ResearchGuaranteeItem("四成可能", "5000", "(5锅)", "2666.4", "(6锅)", "2000", "(5锅)", "1400", "(6锅)", "1000", "(3锅)"),
        ResearchGuaranteeItem("十分微妙", "3750", "(7锅)", "1999.8", "(7锅)", "1500", "(7锅)", "1050", "(8锅)", "750", "(4锅)"),
        ResearchGuaranteeItem("较低可能", "2500", "(10锅)", "1333.2", "(11锅)", "1000", "(10锅)", "700", "(11锅)", "500", "(5锅)"),
        ResearchGuaranteeItem("不大可能", "1250", "(20锅)", "666.6", "(21锅)", "500", "(20锅)", "350", "(22锅)", "250", "(10锅)")
    )
    
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        // 表头
        item {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colorScheme.primaryContainer)
                    .padding(8.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Text(
                    text = "档位",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
                Text(
                    text = "五火",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
                Text(
                    text = "四火",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
                Text(
                    text = "三火",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
                Text(
                    text = "二火",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
                Text(
                    text = "一火",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
            }
        }
        
        // 数据行
        itemsIndexed(researchData) { index, item ->
            // 计算渐变色 - 从绿色(一定成功)到红色(不大可能)
            val gradientColor = when (index) {
                0 -> Color(0xFF4CAF50) // 累计必定成功 - 深绿
                1 -> Color(0xFF66BB6A) // 一定成功 - 绿色
                2 -> Color(0xFF81C784) // 基本稳了 - 浅绿
                3 -> Color(0xFF9CCC65) // 希望很大 - 黄绿
                4 -> Color(0xFFAED581) // 好感很得 - 浅黄绿
                5 -> Color(0xFFFFEB3B) // 勉强及格 - 黄色
                6 -> Color(0xFFFFD54F) // 成功过半 - 浅黄
                7 -> Color(0xFFFFB74D) // 四成可能 - 橙黄
                8 -> Color(0xFFFF8A65) // 十分微妙 - 橙色
                9 -> Color(0xFFFF7043) // 软硬可能 - 深橙
                10 -> Color(0xFFE57373) // 不大可能 - 红色
                else -> MaterialTheme.colorScheme.surface
            }
            
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(gradientColor.copy(alpha = 0.3f))
                    .padding(8.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 档位列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 根据索引决定是否换行显示
                    if (index == 0) {
                        // "累计必定成功" 不换行
                        Text(
                            text = item.level,
                            fontSize = 11.sp,
                            textAlign = TextAlign.Center,
                            fontWeight = FontWeight.Medium
                        )
                    } else {
                        // 其他档位按每两个字换行
                        val levelText = item.level
                        if (levelText.length >= 2) {
                            Text(
                                text = levelText.take(2),
                                fontSize = 11.sp,
                                textAlign = TextAlign.Center,
                                fontWeight = FontWeight.Medium
                            )
                            if (levelText.length > 2) {
                                Text(
                                    text = levelText.drop(2),
                                    fontSize = 11.sp,
                                    textAlign = TextAlign.Center,
                                    fontWeight = FontWeight.Medium
                                )
                            }
                        } else {
                            Text(
                                text = levelText,
                                fontSize = 11.sp,
                                textAlign = TextAlign.Center,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }
                
                // 五火菜列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = item.fiveFireValue,
                        fontSize = 11.sp,
                        textAlign = TextAlign.Center
                    )
                    if (item.fiveFirePots.isNotEmpty()) {
                        Text(
                            text = item.fiveFirePots,
                            fontSize = 10.sp,
                            textAlign = TextAlign.Center,
                            color = Color.Gray
                        )
                    }
                }
                
                // 四火菜列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = item.fourFireValue,
                        fontSize = 11.sp,
                        textAlign = TextAlign.Center
                    )
                    if (item.fourFirePots.isNotEmpty()) {
                        Text(
                            text = item.fourFirePots,
                            fontSize = 10.sp,
                            textAlign = TextAlign.Center,
                            color = Color.Gray
                        )
                    }
                }
                
                // 三火菜列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = item.threeFireValue,
                        fontSize = 11.sp,
                        textAlign = TextAlign.Center
                    )
                    if (item.threeFirePots.isNotEmpty()) {
                        Text(
                            text = item.threeFirePots,
                            fontSize = 10.sp,
                            textAlign = TextAlign.Center,
                            color = Color.Gray
                        )
                    }
                }
                
                // 二火菜列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = item.twoFireValue,
                        fontSize = 11.sp,
                        textAlign = TextAlign.Center
                    )
                    if (item.twoFirePots.isNotEmpty()) {
                        Text(
                            text = item.twoFirePots,
                            fontSize = 10.sp,
                            textAlign = TextAlign.Center,
                            color = Color.Gray
                        )
                    }
                }
                
                // 一火菜列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = item.oneFireValue,
                        fontSize = 11.sp,
                        textAlign = TextAlign.Center
                    )
                    if (item.oneFirePots.isNotEmpty()) {
                        Text(
                            text = item.oneFirePots,
                            fontSize = 10.sp,
                            textAlign = TextAlign.Center,
                            color = Color.Gray
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun EquipResearchGuaranteeContent() {
    // 厨具研发保底数据 - 根据图片数据填入
    val equipResearchData = listOf(
        EquipResearchGuaranteeItem("累计必定成功", "20000", "", "2500", "", "1250", ""),
        EquipResearchGuaranteeItem("一定成功", "10000", "", "2500", "", "1250", ""),
        EquipResearchGuaranteeItem("基本稳了", "9000", "(3锅)", "", "", "", ""),
        EquipResearchGuaranteeItem("希望很大", "8000", "(3锅)", "", "", "", ""),
        EquipResearchGuaranteeItem("好像很稳", "7000", "(3锅)", "", "", "", ""),
        EquipResearchGuaranteeItem("勉强及格", "6000", "(4锅)", "", "", "", ""),
        EquipResearchGuaranteeItem("成功过半", "5000", "(4锅)", "", "", "", ""),
        EquipResearchGuaranteeItem("四成可能", "4000", "(5锅)", "", "", "", ""),
        EquipResearchGuaranteeItem("十分微妙", "3000", "(7锅)", "", "", "", ""),
        EquipResearchGuaranteeItem("较低可能", "2000", "(10锅)", "", "", "", ""),
        EquipResearchGuaranteeItem("不大可能", "1000", "(20锅)", "", "", "", "")
    )
    
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        // 表头
        item {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colorScheme.primaryContainer)
                    .padding(8.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Text(
                    text = "档位",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1.5f),
                    textAlign = TextAlign.Center
                )
                Text(
                    text = "三火",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
                Text(
                    text = "二火",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
                Text(
                    text = "一火",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center
                )
            }
        }
        
        // 数据行
        itemsIndexed(equipResearchData) { index, item ->
            // 计算渐变色 - 从绿色(一定成功)到红色(不大可能)
            val gradientColor = when (index) {
                0 -> Color(0xFF4CAF50) // 累计必定成功 - 深绿
                1 -> Color(0xFF66BB6A) // 一定成功 - 绿色
                2 -> Color(0xFF81C784) // 基本稳了 - 浅绿
                3 -> Color(0xFF9CCC65) // 希望很大 - 黄绿
                4 -> Color(0xFFAED581) // 好像很稳 - 浅黄绿
                5 -> Color(0xFFFFEB3B) // 勉强及格 - 黄色
                6 -> Color(0xFFFFD54F) // 成功过半 - 浅黄
                7 -> Color(0xFFFFB74D) // 四成可能 - 橙黄
                8 -> Color(0xFFFF8A65) // 十分微妙 - 橙色
                9 -> Color(0xFFFF7043) // 较低可能 - 深橙
                10 -> Color(0xFFE57373) // 不大可能 - 红色
                else -> MaterialTheme.colorScheme.surface
            }
            
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(gradientColor.copy(alpha = 0.3f))
                    .padding(8.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 档位列 - 不换行显示
                Text(
                    text = item.level,
                    fontSize = 11.sp,
                    modifier = Modifier.weight(1.5f),
                    textAlign = TextAlign.Center,
                    fontWeight = FontWeight.Medium
                )
                
                // 三火列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = item.threeFireValue,
                        fontSize = 11.sp,
                        textAlign = TextAlign.Center
                    )
                    if (item.threeFirePots.isNotEmpty()) {
                        Text(
                            text = item.threeFirePots,
                            fontSize = 10.sp,
                            textAlign = TextAlign.Center,
                            color = Color.Gray
                        )
                    }
                }
                
                // 二火列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = item.twoFireValue,
                        fontSize = 11.sp,
                        textAlign = TextAlign.Center
                    )
                    if (item.twoFirePots.isNotEmpty()) {
                        Text(
                            text = item.twoFirePots,
                            fontSize = 10.sp,
                            textAlign = TextAlign.Center,
                            color = Color.Gray
                        )
                    }
                }
                
                // 一火列
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = item.oneFireValue,
                        fontSize = 11.sp,
                        textAlign = TextAlign.Center
                    )
                    if (item.oneFirePots.isNotEmpty()) {
                        Text(
                            text = item.oneFirePots,
                            fontSize = 10.sp,
                            textAlign = TextAlign.Center,
                            color = Color.Gray
                        )
                    }
                }
            }
        }
    }
}

// 数据类定义
private data class ResearchGuaranteeItem(
    val level: String,
    val fiveFireValue: String,
    val fiveFirePots: String,
    val fourFireValue: String,
    val fourFirePots: String,
    val threeFireValue: String,
    val threeFirePots: String,
    val twoFireValue: String,
    val twoFirePots: String,
    val oneFireValue: String,
    val oneFirePots: String
)

// 厨具研发保底数据类定义
private data class EquipResearchGuaranteeItem(
    val level: String,
    val threeFireValue: String,
    val threeFirePots: String,
    val twoFireValue: String,
    val twoFirePots: String,
    val oneFireValue: String,
    val oneFirePots: String
)
